【发布时间】:2012-01-14 17:17:00
【问题描述】:
更新:用char string[sizeof buffer - 1]正确初始化字符串已经解决了崩溃问题,但我仍然很好奇有多个标点符号与它有什么关系!
我正在尝试从“一些文本”形式的文件中读取字符串。到目前为止,将sscanf 与\"%[^\"]\" 模式一起使用对我来说非常有效,但是一旦我开始在字符串中添加标点符号,程序就开始崩溃了。
似乎只有在使用多个标点符号时才会出现错误,无论它是什么标点符号或标记的位置。无论文件中带有标点符号的行的位置如何,它也会发生(即,即使最后一行没有标点符号,错误仍然会发生)。
不管怎样,下面是我目前的代码:
char* func(char* f_name);
FILE* file = get_file(f_name,"r"); // a short function I wrote to get the
// file pointer from the current
// directory. The error is almost
// certainly not here.
if (file == 0) {
print("Unable to load file\nExiting...");
exit(-1);
}
char* pattern = "\"%[^\"]\"";
int read_args = -1;
char* string; // string size is unknown until read
char buffer[1200]; // i expect very long line of data in the file
while ( fgets( buffer, sizeof(buffer), file ) != NULL ) {
printf("found line: %s\n",buffer);
read_args = sscanf(buffer, pattern, string);
printf("num args: %d\n",read_args);
printf("read value: %s\n", string);
}
fclose(file);
return string;
}
以下是我尝试过的一些数据。在标记为“不成功”的地方,程序将编译、运行所有内容,并在退出前崩溃。
"test test test" // successful
"test, test test" // successful
"test test; test" // successful
"test, test, test" // unsuccessful
"test; test. test," // unsuccessful
如果此问题得到解决,我计划使用更复杂的模式,并且在发生此错误之前已成功读取模式 %d \"%[^\"]\" \"%[^\"]\" 的数据。提前感谢您的任何回答。
【问题讨论】:
标签: c whitespace scanf punctuation