我有一个包含 N 行的文件 (MyFile.txt),其中一个包含 7 个字段:
(id_artist: int, artist: char, id_song: int, song: char, duration: int, year: int, valoration: int)
它们都是用空格(' ')隔开的。我需要一个函数,给定歌曲的 ID (int),返回具有相同 ID 的歌曲的持续时间。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int ID;
FILE *fp = fopen("MyFile.txt","w");
fprintf(fp,"100 Lennon 1100 Imagine 181 1977 1\n123 Queen 1122 KQueen 190 1983 2\n144 Nirvana 1144 Polly 175 1989 3\n");
fclose(fp);
printf("Ingrese id: ");
scanf("%d",&ID);
int res = duracion(ID);
printf(res);
return 0;
}
int duracion(int id){
char line[100], artista[30], nombre[30];
int id_art, id_song, dur, ano, valoracion;
FILE *file = fopen("MyFile.txt","r");
while( fgets(line,100,file) != NULL)
{
//printf(line);
sscanf(line,"%d %s %d %s %d %d %d", &id_art, artista, &id_song, nombre, &dur, &ano, &valoracion);
if(id == id_song){
return dur;
}
}
return 0;
}
如果指示的行存在,该函数实际上会找到它,但该函数永远不会返回 0 或 1。 如果我取消注释行并搜索不存在的 id,我会得到如下输出:
100 Lennon 1100 Imagine 181 1977
d123 Queen 1122 KQueen 190 1983 2
<144 Nirvana 1144 Polly 175 1989 3
é
我调试了代码,试图找到问题所在,但我不明白。
最佳答案
printf(res); //needed specifier %d
您在这里忘记了 printf
中的格式说明符。
注意-另外,您在函数中打开文件后忘记关闭它。
关于c - 使用 fgets 获取垃圾读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33664746/