0

I am having trouble reading all content of a single text file into a string. Whenever there is a line break it does not keep the previous strings.

For example if the file contained:

this is stack overflow
and it is cool

The only thing that the string would have after reading the file is " it is cool"

here is the code:

FILE *inputFilePtr;
        inputFilePtr = fopen(inputFileName, "r");
        char plainText[10000];

        // if the file does not exist
        if (inputFilePtr == NULL)
        {
            printf("Could not open file %s", inputFileName);
        }

        // read the text from the file into a string
        while (fgets(plainText, "%s", inputFilePtr))
        {
            fscanf(inputFilePtr, "%s", plainText);
        }
        printf("%s\n", plainText);
        fclose(inputFilePtr);

Any Help is greatly appreciated!

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
  • 1
    Check this: https://stackoverflow.com/questions/174531/how-to-read-the-content-of-a-file-to-a-string-in-c – Buddhima Gamlath Apr 06 '20 at 16:41
  • Please [edit] your question and make clear what is the expected result and what do you actually get. Please show the complete code to allow compiling and running your program. ([mre]). Please read the documentation of `fgets`. Your use is wrong. – Bodo Apr 06 '20 at 16:43
  • 1
    `char *fgets(char *s, int size, FILE *stream);` You use fgets with wrong format – Hitokiri Apr 06 '20 at 16:44
  • Always compile with a healthy set of warnings enabled (`-Wall -Wextra` for gcc and clang), and pay attention to them. – Shawn Apr 06 '20 at 17:04

1 Answers1

0

If you want to display all file contents try :

    FILE *inputFilePtr;
    inputFilePtr = fopen(inputFileName, "r");
    char plainText[10000];

    // if the file does not exist
    if (inputFilePtr == NULL)
    {
        printf("Could not open file %s", inputFileName);
    }

    // read the text from the file into a string
    while (!feof(inputFilePtr)) //while we are not at the end of the file
    {
       fgets(plainText, "%s", inputFilePtr);
       printf("%s\n", plainText);
    }
     fclose(inputFilePtr);

Or if you want to display all file contents in one string use :

#include <string.h>
 int main()
 {
   FILE *inputFilePtr;
    inputFilePtr = fopen(inputFileName, "r");
    char plainText[10000];
    char buffer[10000];


  // if the file does not exist
    if (inputFilePtr == NULL)
    {
        printf("Could not open file %s", inputFileName);
    }

    // read the text from the file into a string
    while (!feof(inputFilePtr))
    {
      fgets(buffer, "%s", inputFilePtr);
      strcat(plainText,buffer);
    }
     printf("%s\n", plainText);
     fclose(inputFilePtr);

 }
Joe
  • 43
  • 1
  • 7