我正在尝试逐行读取文件,并标记每行,这些行的字符串由空格和制表符分隔。但是,当我运行程序时,尝试打印令牌时出现Segmentation Fault
错误。我不明白为什么会这样,因为我使用缓冲区作为字符串来标记和检查标记是否为空。下面是我的代码:
#include <stdio.h>
#include <stdlib.h>
#define MAX_LINE_LENGTH 70
int main(void)
{
FILE * testFile;
char buf[MAX_LINE_LENGTH];
testFile = fopen("test_file.txt","r");
if (testFile == NULL)
{
printf("Cannot open test_file.txt.\n");
exit(0);
}
while (fgets(buf,sizeof(buf),testFile) != NULL) {
char *token = strtok(buf," \t");
while (token != NULL)
{
token = strtok(NULL," \t");
if (token != NULL) {
printf("%s\n",token);
}
}
}
exit(1);
}
下面是test_file.txt
的内容:
String1 String2 String3
String4 String5 String6
String7 String8 String9