(これは tcsh の C、Unix 用です。)
文字列を外部ファイル (出力) に書き込んでから、出力をファイル入力と比較しようとしています。出力がそのファイルに存在する場合、「レコードが見つかりました」と出力したいと思います。そのファイルに出力が存在しない場合は、「レコードが見つかりません」と出力します。
出力と入力を比較するために while ループを使用しています。レコードが見つかった場合にループが終了し、「レコードが見つかりました」と出力するビットが機能しています。
「else」部分が機能しません。これについては、コード内の私のコメントを参照してください。
テキスト、メモ、グーグルを 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;
}