2016-04-21 130 views
0

因此,我应该编写一段代码,打开一个名为“单词”的文件,并将文件中的最后一个单词写入名为“lastword”的文件。这是我到目前为止:如何读取文本文件中的最后一个单词和C中的另一个文本文件?

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


fclose(fp) 
fclose(f); 

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

回答

1

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

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

+0

可能是最好的方法,尤其是如果您的文件很大。如果你的“单词”比文件的末尾大,那么可能会发生麻烦。 –

+0

是的,确切地说。搜索继续,直到找到该单词。 – fluter

+0

好方法!但是,在文本模式下读取文件末尾是不可移植的:标准中写明“7.21.9.2:*对于文本流,任一偏移量应为零,或者偏移量应为先前成功调用函数返回的值函数在与同一个文件相关的数据流上,因此应该是SEEK_SET。*“ - 另见:http://www.cplusplus.com/reference/cstdio/fseek/ – Christophe

1

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

简单的方法

一个简单的办法是循环的文字阅读:

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; 
} 
相关问题