Home > Enterprise >  Invalid File Content When trying to read file in C
Invalid File Content When trying to read file in C

Time:10-08

I am trying to read a file in C. First I am calculating the lines in the file:

int main(int argc, char* argv[])
{
  if (argc < 2)
  {
    printf("No file specified");
    exit(1);
  }

  FILE* pFile;
  char currentCharacter;
  int lines = 1;

  pFile = fopen(argv[1], "r");

  for (currentCharacter = getc(pFile); currentCharacter != EOF; currentCharacter = getc(pFile))
  {
    if (currentCharacter == '\n') lines  ;
  }

  ...
}

After calculating the lines in the file, I tried reading one by one, like this:

char currentLine[255];

for (int i = 1; i <= lines; i  )
{
  fgets(currentLine, 255, pFile);

  printf("%s\n", currentLine);
}

fclose(pFile);

But everytime I run it, I am getting this output:

²a

When I try to remove the for loop and place fgets() and printf() outside, it prints NOTHING

If you are wondering, here is the content of the file I am trying to read:

test.txt

hi
test2

NOTE: The file is being successfully opened as it is counting the lines correctly.

CodePudding user response:

As said in the comments, no need to count the lines. Just stop when there is nothing more to read. That is, when fgets returns NULL.

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

int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        printf("No file specified");
        exit(1);
    }

    FILE* pFile = fopen(argv[1], "r");
    if(pFile==NULL)
    {
        printf("File is not found");
        exit(1);
    }

    char currentLine[256];

    while(fgets(currentLine, 256, pFile))
    {
        printf("%s", currentLine);
    }

    return 0;
}
  • Related