您好,我尝试在 C 程序中使用 fgets 来查看 .csv 文件中的一行中是否存在某个名称。如果是,则将其保存在数组中然后返回。现在,它保存了 .csv 文件中的所有行,我不确定为什么。
C文件:
void FindRecord(char *filename, char *name, char record[]) {
char *temp = record; //temp save record
FILE *q = fopen(filename, "r"); //check that ths inputed .csv file exists
if (q == NULL ) { //if it doesn't, then print error message and exit
printf("This .csv does not exist");
exit(1); //terminate with error message
}
while(!feof(q)) { //while I'm not at the end of the file
fgets(temp, 1000, q); //Reads a line @ a time
for (int i = 0; i < 1000; i++) {
if(temp[i] == *name) {
record[i] = temp[i];
name++;
}
}
printf("%s", record);
}
fclose(q);
}
.csv 文件:
Kevin, 123-456-7890
Sally, 213-435-6479
Megan, 415-336-8790
现在,当我运行该程序时,它返回了 3 行。我想要的是,如果 *name
指向名称 "Kevin"
并且它带有 temp,它只会返回:Kevin, 123-456-7890
最佳答案
Right now whats happening when I run the program is that it returns the 3 lines.
我不明白这怎么可能。您只有一个数组可以在其中返回结果。我相信您的代码打印所有三行,但它只会返回最后一行。
I want iso that if
*name
points to the name"Kevin"
and it comes withtemp
, it'll just return:Kevin, 123-456-7890
那么,您的代码在这方面有几个问题。其中最重要的是:
虽然它执行了一些逐个字符的比较,但它没有任何代码来拒绝匹配失败的行。
它将
temp
设置为指向与record
相同的数组,然后将每一行读入该数组。即使在没有找到匹配项的情况下,这也会覆盖该数组,如果在除最后一次读取之外的一行上找到匹配项,则实际匹配项将丢失。它会在尝试匹配时修改
name
指针,没有在部分匹配的情况下重置它的机制。当尝试匹配名称时,它会愉快地扫描输入行中的
、
分隔符,如果遇到它们,还会扫描名称和输入字符串中的字符串终止符。
关于c - 如何使用 fgets 查找此行是否存在于 .csv 文件中? (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47147188/