2014-10-28 28 views
1

基本上,我試圖把裝有1和0的像一個文件:如何從文件加載布爾值到C中的數組?

10101000 00000000 01010100 
10000000 00000000 00000000 
01101000 11111111 00000000 

,並採取那些具體布爾爲數字將是正確的順序數組。我對fscanf和C語言的一般文件I/O沒有太多經驗,所以它有點粗糙。這是我迄今爲止所擁有的。

#include <stdio.h> 

bool memory[1024]; 
char file; 
char bit; 
int i; 

int main() { 
    file = fopen ("memory.txt", "r"); 
    while (fscanf (file, "%d", bit) != EOF) { 
     i = 0; 
     memory[i] = bit; 
     ++i; 
    } 
} 

當我在編寫本的嘗試,我得到:

./stackexample.c:3:1: error: unknown type name ‘bool’  
bool memory[1024]; 
^ 
./stackexample.c: In function ‘main’: 
./stackexample.c:9:10: warning: assignment makes integer from pointer without a cast  [enabled by default] 
file = fopen ("memory.txt", "r"); 
    ^
./stackexample.c:10:5: warning: passing argument 1 of ‘fscanf’ makes pointer from integer without a cast [enabled by default] 
while (fscanf (file, "%d", bit) != EOF) { 
^ 
In file included from /usr/include/features.h:374:0, 
      from /usr/include/stdio.h:27, 
      from ./stackexample.c:1: 
/usr/include/stdio.h:443:12: note: expected ‘struct FILE * __restrict__’ but argument is of type ‘char’ 
extern int __REDIRECT (fscanf, (FILE *__restrict __stream, 
     ^
./stackexample.c:10:5: warning: format ‘%d’ expects argument of type ‘int *’, but argument 3 has type ‘int’ [-Wformat=] 
while (fscanf (file, "%d", bit) != EOF) { 
^ 

我不明白爲什麼它說未知bool,並且我也不太明白有關從製作一個整數的警告指針。

+1

fscanf是矯枉過正。 fgets和一個循環,用'if'表示0,1和空白就足夠了。你只是使用fscanf錯誤(缺少&) – deviantfan 2014-10-28 20:47:11

+1

類型'bool'需要''頭文件(直接名稱是'_Bool'),編譯器必須符合C99/C11標準。 – 2014-10-28 20:47:13

+0

'bool'不是老C語言中的一種類型。如果它不可用,請隨意使用'unsigned char'。 'fopen()'返回一個'FILE *';你出於某種原因將它分配給一個'char'。 – 2014-10-28 20:47:35

回答

2

C沒有bool類型 - 它是C++。如果你使用C99標準,你可以包含stdbool.h標題,你會得到bool作爲typedef。這將解決你的第一個問題。

您不應該在fscanf()中使用%d讀取該文件,因爲您會得到整數,例如10101000。您應該指定寬度或讀取數據作爲字符(與%c) - 親自我會去第二個選項。當然,你應該「掃描」到一個正確的類型的臨時變量,然後複製到你的數組 - 這將解決警告。

0

用盡可能少的修改可能:

#include <stdio.h> 
#include <stdbool.h> 
#include <assert.h> 

bool memory[1024]; 
char file; 
char bit; 
int i; 

int main() { 
    FILE * file = fopen ("memory.txt", "r"); 
    assert(file); 
    while (fscanf (file, "%c", &bit) != EOF) { 
     printf("%c",bit); 
     assert(i < 1024); 
     if (bit == '1') 
      memory[i++] = true; 
     if (bit == '0') 
      memory[i++] = false; 
    } 
    fclose(file); 
} 
0

你是不是正確的定義文件,也代替使用布爾,你可以使用int,只是檢查它是否是一個1或0的,如果別人聲明

另外不要忘記你的fclose statment來關閉文件。

#include <stdio.h> 
#define FILENAME "/your/file/path" 
int main() 
{ 
    int memory[1024]; 
    int bit; 
    int i; 
    FILE *myfile; //Define file 

    myfile = fopen (FILENAME, "r"); //Open file 
    while (fscanf(myfile,"%i",&bit) != EOF) // Read file 
    { 
     i = 0; 
     memory[i] = bit; 
     ++i; 
    } 

    fclose(myfile); 
    return 0; 
} 
相關問題