我正在尝试阅读像这样的文本文件
1234567890 1234
9876543210 22
到我的程序中的List结构中。我通过fgets()读取文件然后使用strtok分隔数字,将它们放入变量然后最终进入List。但是,我发现在执行此操作并打印生成的字符串时,strtok始终将最后一行中的最后一个字符串设为NULL,从而导致分段错误。
fgets(fileOutput,400,filePointer); //Read in a line from the file
inputPlate = strtok(fileOutput," "); // Take the first token, store into inputPlate
while(fileOutput != NULL)
{
string = strtok(NULL," ");
mileage = atoi(string); //Convert from string to integer and store into mileage
car = initializeCar(mileage,dateNULL,inputPlate);
avail->next = addList(avail->next,car,0);
fgets(fileOutput,400,filePointer);
inputPlate = strtok(fileOutput," ");
}
如何解决此问题?
答案 0 :(得分:2)
用fgets()
逐行阅读文本文件是好的
不检查fgets()
的返回值很弱。这导致OP的代码处理超出最后一行。
// Weak code
// fgets(fileOutput,400,filePointer); //Read in a line from the file
// ...
// while(fileOutput != NULL)
// {
最好检查fgets()
的结果以确定输入何时完成:
#define LINE_SIZE 400
...
while (fgets(fileOutput, LINE_SIZE, filePointer) != NULL)
{
然后处理字符串。评估解析成功的一种简单方法是将" %n"
附加到sscanf()
格式以记录扫描的偏移量。
char inputPlate[LINE_SIZE];
int mileage;
int n = -1;
sscanf(fileOutput, "%s%d %n", inputPlate, &mileage, &n);
// Was `n` not changed? Did scanning stop before the string end?
if (n < 0 || fileOutput[n] != '\0') {
Handle_Bad_input();
break;
} else {
car = initializeCar(mileage, dateNULL, inputPlate);
avail->next = addList(avail->next,car,0);
}
}
答案 1 :(得分:1)
您可以使用fscanf()
编写一个更简单的解析器:
FILE *filePointer;
... // code not shown for opening the file, initalizing the list...
char inputPlate[32];
int mileage;
while (fscanf(filePointer, "%31s%d", inputPlate, &mileage) == 2) {
car = initializeCar(mileage, dateNULL, inputPlate);
avail->next = addList(avail->next, car, 0);
}