所以我的文件有表格full_file_path #的数据,例如,
C:/dev/Java/src/java/util/concurrent/ConcurrentHashMap.java 212
C:/dev/Java/src/java/util/HashMap.java 212
C:/dev/Java/src/java/lang/CharacterData02.java 190
C:/dev/Java/src/java/lang/CharacterData0E.java 190
C:/dev/Java/src/java/nio/DirectCharBufferS.java 123
C:/dev/Java/src/java/nio/DirectCharBufferU.java 123
...我试着用
int dup;
char file[MAX_LINE];
...
FILE *fp;
fp = fopen("OUTPUT100.txt", "r");
while (fscanf(fp, "%s %d\n", &file, &dup) == 1) {
printf("%s %d\n", file, dup);
}
fclose(fp);但是,输出是垃圾级的
has 0 duplciate lines of code
RJ9 has 0 duplciate lines of code
has 0 duplciate lines of code
▒▒" has 0 duplciate lines of code
has 0 duplciate lines of code
"A▒ has 0 duplciate lines of code
has 0 duplciate lines of code
7▒cw has 0 duplciate lines of code
has 0 duplciate lines of code
has 0 duplciate lines of code我做错了什么?
编辑:我的“仍然吐出垃圾”的评论只是脑子里的放屁。我在was循环下面的一个循环中有一个printf,这个循环正在吐出垃圾。在滚动了几百行之后,我开始看到合理的数据。将打印本注释掉,就产生了预期的结果。工作读取使用while (fscanf(fp, "%s %d\n", file, &dup) == 2)。谢谢大家。
发布于 2015-11-02 20:00:03
像这样修改循环调用
while (fscanf(fp, "%s %d\n", file, &dup) == 2) {正如@mjswartz所说,file是一个数组,当您将它传递给fscanf时,它将衰减到char*。此外,fscanf将返回它设法检索的参数数,您将扫描每行2个变量。
发布于 2015-11-02 19:59:42
好的,fscanf返回成功格式说明符的数量,因此它在成功时返回2,并且检查它是否返回1。您可能想要检查EOF字符,然后停止从那里读取。
此外,file变量是一个数组,可以用作指针,因此不应该尝试引用它。
while (1)
{
r = fscanf(fp, "%s %d\n", file, &dup);
if( r == EOF )
break;
printf("%s %d\n", file, dup);
}发布于 2015-11-03 19:45:08
关于这一行:
while (fscanf(fp, "%s %d\n", &file, &dup) == 1) {fscanf()返回成功的输入/转换数
也就是说,如果它是成功的,并且格式字符串有2个转换参数,那么它将返回2,而不是1。
请阅读/理解fscanf()手册页
格式字符串不应该有尾随'\n‘(与printf()不同,后者几乎总是尾随'\n')
要使用任何“剩馀的”空白(如换行符),请在格式字符串中放置一个前导空格。
当前格式说明符‘’%1!‘’没有最大长度修饰符,因此输入文件中的数据可能会超出可用的输入缓冲区,从而导致未定义的行为,从而导致seg错误事件。
注意:在C中,数组的名称退化为指向数组的第一个字节的指针,因此不要使用数组的地址:file
建议:
while (fscanf(fp, " %#s %d\n", file, &dup) == 2) { 其中#是MAX_LINE-1的值。
绝对不可能将已发布的代码输出为输出的文本。
建议张贴实际代码、实际输出和预期输出。
注意:file是char数组的糟糕名称。建议一些有意义的东西,比如buffer
https://stackoverflow.com/questions/33485740
复制相似问题