如何在字符串中保存文本文件的内容

问题描述:

这是为什么当我在输出中显示字符串时,我拥有所有单词但在最后一行中有一个奇怪的符号,一个ASCII随机符号...如何在字符串中保存文本文件的内容

我的目标是保存一个字符串中的所有单词来操作它。

例如,我有这个文件:

Mario 


Paul 


Tyler 

我如何保存所有单词串?

#include <stdio.h> 
#include <stdlib.h> 

/* run this program using the console pauser or add your own getch, system("pause") or input loop */ 

int main(int argc, char *argv[]) { 
    int l,i=0,j=0,parole=0; 
    char A[10][10]; 
    char leggiparola; 
    char testo[500]; 
    FILE*fp; 
    fp=fopen("parole.txt","r"); 
    if(fp!=NULL) 
    { 
     while(!feof(fp)) 
     { 
      fscanf(fp,"%c",&leggiparola); 
      printf("%c", leggiparola); 
      testo[j]=leggiparola; 
      j++; 
     } 
    } 
    fclose(fp); 
    printf("%s",testo); 
    return 0; 
} 
+5

也许是因为您错误地使用了'feof'。请参阅[为什么“while(!feof(file))”总是错误?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong)更好地测试从'fscanf'返回值,以保证它确实扫描了你想要的内容。 –

+1

请注意,当打开文件失败时,您不应该调用'fclose()'。由于您不使用命令行参数,所以编写'int main(void)'会更清晰。 –

除了while(!feof(fp)) being "always wrong"你错过0 -terminate结果字符串。

为此放置

testo[j] = '\0' 

只是while -loop后。

+0

非常感谢您的帮助! – Paky100

而不是使用的fscanf的,尝试用GETC:

int leggiparola; /* This need to be an int to also be able to hold another 
        unique value for EOF besides 256 different char values. */ 

... 

while ((leggiparola = getc(fp)) != EOF) 
{ 
    printf("%c",leggiparola); 
    testo[j++] = leggiparola; 
    if (j==sizeof(testo)-1) 
     break; 
} 
testo[j] = 0; 
+1

'leggiparola'需要键入'int'(根据OP的代码,不是这种情况),以便您的提案能够正常工作。 – alk

+0

'getc'与'char'一起工作,所以应该没有问题。 –

+0

getc()'返回EOF'的时候会出现问题。推荐进一步阅读:http://stackoverflow.com/questions/7119470/int-c-getchar – alk

这里的fslurp。由于需要手动增加缓冲区,所以我有点麻烦。

/* 
    load a text file into memory 

*/ 
char *fslurp(FILE *fp) 
{ 
    char *answer; 
    char *temp; 
    int buffsize = 1024; 
    int i = 0; 
    int ch; 

    answer = malloc(1024); 
    if(!answer) 
    return 0; 
    while((ch = fgetc(fp)) != EOF) 
    { 
    if(i == buffsize-2) 
    { 
     if(buffsize > INT_MAX - 100 - buffsize/10) 
     { 
      free(answer); 
      return 0; 
     } 
     buffsize = buffsize + 100 * buffsize/10; 
     temp = realloc(answer, buffsize); 
     if(temp == 0) 
     { 
     free(answer); 
     return 0; 
     } 
     answer = temp; 
    } 
    answer[i++] = (char) ch; 
    } 
    answer[i++] = 0; 

    temp = realloc(answer, i); 
    if(temp) 
    return temp; 
    else 
    return answer; 
}