How to read in the last word in a text file and into another text file in C?

时间:2016-04-21 22:28:01

标签: c file-io

SO i'm supposed to write a block of code that opens a file called "words" and writes the last word in the file to a file called "lastword". This is what I have so far:

FILE *f; 
FILE *fp;
char string1[100];
f = fopen("words","w"); 
fp=fopen("lastword", "w");
fscanf(f, 


fclose(fp)
fclose(f);

The problem here is that I don't know how to read in the last word of the text file. How would I know which word is the last word?

2 个答案:

答案 0 :(得分:1)

This is similar to what the tail tool does, you seek to a certain offset from the end of the file and read the block there, then search backwards, once you meet a whitespace or a new line, you can print the word from there, that is the last word. The basic code looks like this:

char string[1024];
char *last;
f = fopen("words","r");
fseek(f, SEEK_END, 1024);
size_t nread = fread(string, 1, sizeof string, f);
for (int I = 0; I < nread; I++) {
    if (isspace(string[nread - 1 - I])) {
        last = string[nread - I];
    }
}
fprintf(fp, "%s", last);    

If the word boundary is not find the first block, you continue to read the second last block and search in it, and the third, until your find it, then print all the characters after than position.

答案 1 :(得分:1)

There are plenty of ways to do this.

Easy way

One easy approach would be to to loop on reading words:

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

However this takes a word as any combination of characters separated by space. Note the use of the with filed in the scanf() format to make sure that there will be no buffer overflow.

More exact way

Building on previous attempt, if you want a stricter definition of words, you can just replace the call to scanf() with a function of your own:

    rc=read_word(f, string1, 100); 

The function would be something like:

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;
}