我正在尝试读取这样的文本文件
1234567890 1234
9876543210 22
在我的程序中把放入List结构体中。我通过fgets()读取文件,然后使用strtok将数字分开,将它们放入变量中,最后放入列表中。然而,我发现在这样做并打印结果字符串时,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," ");
}
如何解决这个问题?
使用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] != ' ') {
Handle_Bad_input();
break;
} else {
car = initializeCar(mileage, dateNULL, inputPlate);
avail->next = addList(avail->next,car,0);
}
}
您可以使用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);
}