[英]How do use fgets to find if this line exists in .csv file? (C)
嗨,我打算在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行。 我想要iso如果*name
指向名稱"Kevin"
並且它帶有temp,它將返回: Kevin, 123-456-7890
現在,當我運行程序時發生的事情是它返回了3行。
我不知道怎么可能。 您只有一個要在其中返回結果的數組。 我可以相信您的代碼會打印所有三行,但只會返回最后一行。
我想要iso如果
*name
指向名稱"Kevin"
並且它帶有temp
,它將返回:Kevin, 123-456-7890
好吧,您的代碼在這方面有幾個問題。 其中最重要的是:
盡管它執行逐個字符的比較,但是它在任何地方都沒有代碼來拒絕不匹配的行。
它將temp
設置為指向與record
相同的數組,然后將每一行讀入該數組。 即使沒有找到匹配項,這也會覆蓋該數組,並且如果在最后一次讀取以外的其他行上找到了匹配項,則實際匹配項將丟失。
它會在嘗試匹配name
指針時修改name
指針,而在部分匹配的情況下,沒有用於重置它的機制。
當嘗試匹配名稱時,它將巧妙地掃描輸入行中的,
分隔符,如果涉及到它們,則掃描名稱和輸入字符串中的字符串終止符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.