方法は非常に簡単です...あなたはほとんどそれを持っています:
より完全な図を見てみましょう。
int main() {
char line[256]; /* a long enough line */
char *p;
FILE *fin, *fout;
fin = fopen("somefile.txt", "r");
fout = stderr; /* you can change this to another open file later */
while(!feof(fin)) {
fgets(line, sizeof(line), fin);
p = strstr(line, "class states");
if ( p ) { /* we found the line */
/* okay here p is a pointer that points to
* the beginning of the phrase class states but we want just
12 (or whatever) before the /1000 so we use strchr this time */
p = strchr(line, '/'); /* now we are at the first slash */
*p = 0; /* change the slash(/) to NUL and that
* makes the line end at number 12 */
fprintf(fout, "%s\n", line);
}
}
}
これは、少しエラーチェックを行う少しクリーンな方法です。タブ付きコードの大きなブロックを避けるために、if (p) ロジックを逆にしたことに注意してください。
int main() {
char line[256]; /* a long enough line */
char *p;
FILE *fin, *fout;
fin = fopen("somefile.txt", "r");
if ( !fin ) {
fprintf(stderr, "Unable to open `somefile.txt' for reading\n");
return -1;
}
fout = fopen("savedfile.txt", "w");
if ( !fout ) {
fprintf(stderr, "Unable to open `savedfile.txt' for writing\n");
return -1;
}
while(!feof(fin)) {
fgets(line, sizeof(line), fin);
p = strstr(line, "class states");
if ( !p ) { /* we did not find the line */
continue;
}
/* everything below this happens when we find the line */
/* okay when we get here p is a pointer that points to
* the beginning of the phrase class states but we want just
12 (or whatever) before the /1000 so we use strchr this time */
p = strchr(line, '/'); /* now we are at the first slash */
if ( !p ) {
fprintf(stderr, "Didn't find a slash in `%s'\n", line);
continue; /* go on to the next line */
}
*p = 0; /* change the slash(/) to NUL and that
* makes the line end at number 12 */
fprintf(fout, "%s\n", line);
}
fclose(fout);
return 0;
}