简体   繁体   中英

How to save in a string the contents of a text file

This is the code why when I show in output the string I have all words but with in the final row a strange symbol , an ASCII random symbol...

My objective is to save in a string all words to operate with it.

For example I have this document:

Mario


Paul


Tyler

How can i save all words in a string??

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

Besides while(!feof(fp)) being " always wrong " you miss to 0 -terminate the result string.

To do so place a

testo[j] = '\0'

just after the while -loop.

Instead of using fscanf, try with 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;

Here's fslurp. I't a bit messy due to the need to grow the buffer manually.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM