如何从文件加载布尔值到C中的数组?

问题描述:

基本上,我试图把装有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

C没有bool类型 - 它是C++。如果你使用C99标准,你可以包含stdbool.h标题,你会得到bool作为typedef。这将解决你的第一个问题。

您不应该在fscanf()中使用%d读取该文件,因为您会得到整数,例如10101000。您应该指定宽度或读取数据作为字符(与%c) - 亲自我会去第二个选项。当然,你应该“扫描”到一个正确的类型的临时变量,然后复制到你的数组 - 这将解决警告。

用尽可能少的修改可能:

#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); 
} 

你是不是正确的定义文件,也代替使用布尔,你可以使用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; 
}