将格式化文件读入C中的char数组

我有一个非常简单的问题。 我需要将文件的内容读入C中的char数组。文件将始终格式化为两列字母,例如:

AB BC EX CD 

每个字母代表图形上的一个顶点,我将在稍后处理。 我已经学会了使用C ++和Java编程,但我并不特别熟悉C语言。

引起我无法弄清楚的问题的是文件多行多长的事实。 我需要每个字母占据数组中的一个插槽,所以在这种情况下它是: array[0] = 'A', array[1] = 'B', array[2] = 'B', array[3] = 'C'等等。

最终我需要数组不包含重复项,但我可以稍后处理。 我在本学期早些时候编写了一个程序,它从一个文件中读取一行内容并且工作正常,因此我复制了大部分代码,但在这种情况下它不起作用。 这是我到目前为止所拥有的:

 #include  #include  int main (int argc, char *argv[]) { int i; int count = 0; char * vertexArray; char ch = '\0'; // open file FILE *file = fopen( argv[1], "r" ); // count number of lines in file while ((ch=fgetc(file)) != EOF) if(ch == '\n') count++; // numbers of vertices is twice the number of lines int size = count*2; // declare vertex array vertexArray = (char*) calloc(size, sizeof(char)); // read in the file to the array for(i=0; i<size; i++) fscanf(file, "%c", &vertexArray[i]); // print the array for(i=0; i<size; i++) printf("%c\n", vertexArray[i]); fclose( file ); } 

我知道我需要测试文件打开并正确读取和诸如此类的东西,但我稍后会添加它。 刚试着读入数组。 在这种情况下,我的输出是8个空白行。 任何帮助都会很棒!

循环遍历文件以计算行数时,文件指针已经位于EOF ,因此您不会在数组中读取任何内容。 最好它与你的最后一个角色的价值相同,但它可能会显示你的分段错误。

你想做的是

 rewind(file); 

在你面前

 //read file into the array 

那么你将从文件的开头开始。 另外,我不确定fgetc如何处理行尾,因为那里通常有一个尾随'\0' 。 另一种方法是使用类似fscanf

 i = 0; while (!feof(file)){ fscanf(file, "%c %c", &vertexArray[i], &vertexArray[i+1]); i++; } 

函数feof(FILE *)检查是否已设置EOF标志,并在您按下EOF停止。

更新:我认为如果你将ch定义为int ch ,它应该工作。 看看这个post。

这是适合我的代码:

 int main (int argc, char *argv[]) { int i; int count = 0; char * vertexArray; int ch, size; FILE *file; file = fopen(argv[1], "r"); while ((ch = fgetc(file) != EOF)) count++; size = count*2; vertexArray = (char*) calloc(size, sizeof(char)); rewind(file); for(i=0; i 

}

新编辑注意fscanf(file, "%c ", &vertexArray[i]);之后的空格fscanf(file, "%c ", &vertexArray[i]); 。 这告诉C你想在阅读完字符后跳过所有的空格。 没有空间,它也会将空白作为一个角色来阅读。 这应该解决它。

fgetc推进文件位置指示器。 您需要使用当前代码返回0,或者在不关心行数的情况下读取行。

当您开始读取数据时,您已经耗尽了文件并计算了行数。 您必须倒回或重新打开该文件。

你需要添加fseek(file, 0, SEEK_SET);

你的代码必须看:

 //Some stuff // declare vertex array vertexArray = (char*) calloc(size, sizeof(char)); fseek(file, 0, SEEK_SET); // read in the file to the array for(i=0; i