如何在 C 语言中读入文本文件中的最后一个单词和另一个文本文件



>所以我应该写一个代码块来打开一个名为"words"的文件,并将文件中的最后一个单词写入一个名为"lastword"的文件中。这是我到目前为止所拥有的:

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

fclose(fp)
fclose(f);

这里的问题是我不知道如何阅读文本文件的最后一个单词。我怎么知道哪个词是最后一个词?

类似于tail工具所做的,您寻求与文件末尾的某个偏移量并读取那里的块,然后向后搜索,一旦遇到空格或换行符,您就可以从那里打印单词,这是最后一个单词。基本代码如下所示:

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

如果单词边界没有找到第一个块,你继续阅读倒数第二个块并在其中搜索,第三个,直到找到它,然后打印比位置之后的所有字符。

有很多方法可以做到这一点。

简单的方法

一种简单的方法是循环阅读单词:

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 归档,以确保不会有缓冲区溢出。

更精确的方法

在之前的尝试的基础上,如果你想要一个更严格的单词定义,你可以用你自己的函数替换对scanf()的调用:

    rc=read_word(f, string1, 100); 

该函数如下所示:

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

最新更新