我有一个非常简单的问题。我需要在C中将文件内容读入到char数组中。该文件将始终格式化为两列字母,例如:
A B
B C
E X
C D
每个字母代表图中的一个顶点,稍后我将处理它。我学过使用C++和Java编程,但对于C并不是特别熟悉。
导致问题的原因是文件有多行。我需要每个字母占据数组中的一个位置,所以在这种情况下,它应该是:
array[0] = 'A',array[1] = 'B',array[2] = 'B',array[3] = 'C'
等等。最终,我需要数组不包含重复项,但我可以稍后处理。本学期早些时候,我写了一个从文件中读取单行整数的程序,它很好用,所以我复制了大部分代码,但在这种情况下不起作用。这是我目前的代码:
#include <stdio.h>
#include <stdlib.h>
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个空行。任何帮助都将非常感激!