(这是用于 tcsh 中的 C、Unix 的。)
我正在尝试将字符串写入外部文件(输出),然后将我的输出与文件输入进行比较。如果该文件中存在输出,我想打印“找到记录”。如果该文件中不存在输出,我想打印“找不到记录”。
我正在使用 while 循环将输出与输入进行比较。我有一点工作,如果找到记录,循环终止并打印“找到记录”。
我无法让“其他”部分工作。请参阅我在代码中对此的评论。
48 小时以来,我一直在阅读我的文字、笔记和谷歌搜索。我似乎无法解决这个问题。
谢谢你的帮助。
/*This program opens a file, compares output to file input*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FILE_NAME "~/MyFiles/File1"
int main() {
FILE *fp;
char *input;
char *output;
output = "MyName";
input = "new name"; /*I get a compiler error if I don't initialize input*/
int found = 0;
/*Open file, write output ("MyName") to file in order to compare below*/
fp = fopen(FILE_NAME, "a+");
fprintf(fp, "%s\n", output);
fclose(fp);
/*Testing to see what it prints, not relevant to my question other than reopening the
file to read in and compare below*/
fp = fopen(FILE_NAME, "r");
fscanf(fp, "%s", input);
printf("\n%s", input);
while (!found) {
if (strcmp(input, "MyName") == 0) {
printf("Record found.");
found = 1;
}
/*This is the part I can't get to work. I don't know what's off.*/
else {
printf("Record not found."); /*Printing this so I can see how many times it's
checking. It never terminates. How do I get it to scan through the file ONCE and then
stop?*/
fscanf(fp, "%s", input);
found = 0; /*I thought this was my loop terminator, but it has no effect.*/
}
}
fclose(fp);
return 0;
}