これにはさまざまな方法があります。
簡単な方法
一つの簡単な方法は、言葉を読んだ上でループにすることです:
f = fopen("words.txt","r"); // attention !! open in "r" mode !!
...
int rc;
do {
rc=fscanf(f, "%99s", string1); // attempt to read
} while (rc==1 && !feof(f)); // while it's successfull.
... // here string1 contains the last successfull string read
は、しかし、これはスペースで区切られた文字の任意の組み合わせとしての単語を取ります。バッファオーバーフローがないことを確認するために、scanf()
形式のwithフィールドを使用することに注意してください。
rc=read_word(f, string1, 100);
:あなたは言葉の厳格な定義をしたい場合は
より正確な方法
ビル前の試みで、あなたは自分自身の機能を()scanf関数の呼び出しを置き換えることができます
この関数は次のようなものになります。
int read_word(FILE *fp, char *s, int szmax) {
int started=0, c;
while ((c=fgetc(fp))!=EOF && szmax>1) {
if (isalpha(c)) { // copy only alphabetic chars to sring
started=1;
*s++=c;
szmax--;
}
else if (started) // first char after the alphabetics
break; // will end the word.
}
if (started)
*s=0; // if we have found a word, we end it.
return started;
}
おそらくファイルが大きい場合はおそらく最も良い方法です。あなたの "言葉"がこれよりも大きい場合は、ファイルの最後から始めると問題が起きる可能性があります。 –
はい、正確です。検索は単語が見つかるまで続きます。 – fluter
ニースのアプローチ!しかし、テキストモードでファイルの最後から読み込むことは移植性がありません。 "7.21.9.2:*テキストストリームの場合、オフセットはゼロでなければなりません。オフセットはftellへの前回の正常呼び出しで返された値です同じファイルに関連付けられたストリーム上で機能し、SEEK_SETとなる。* " - 参照:http://www.cplusplus.com/reference/cstdio/fseek/ – Christophe