0

Basically I'm supposed to make a program that copies the Unix -wc command. Flags -l, -w, -c, and -L are supposed to display # of lines, # of words, # of characters, and # of characters in line, respectively.

I am having trouble reading in a text file (first time doing it in C). I used GDB and discovered my problem lies in reading in the file. After awhile it just reads in null characters for whatever reason.

Please assume everything is right with my code except for reading in the file.

Here is my code:

void readInFile(char** argv, int arg, int addFlags, int argc)
{
   FILE *myFile;
   char c;
   int wordCount = 0, lineCount = 1, longestLine, characterAmount = 0;
   int charactersInLine = 0;

   myFile = fopen(argv[arg], "r");
   if(!myFile)
   {
      printf("%s not found!", argv[arg]);
      exit(EXIT_FAILURE);
   }

   while(c != EOF)
   {
      c = fgetc(myFile);  //Problem lies here and I don't know how to fix it
      putchar(c);
      characterAmount++;
      charactersInLine++;

      if(c == ' ')
         wordCount++;
      if(c == '\n')
      {
      if(charactersInLine > longestLine)
         longestLine = charactersInLine;
      charactersInLine = 0;
      lineCount++;
      wordCount++;
   }
}

Thanks alot

2
Contributors
2
Replies
9
Views
4 Years
Discussion Span
Last Post by ChicagoBears2012
1

fgetc() returns int, not char.

The return type is int to accommodate for the special value EOF, which indicates failure:

The while loop should be this so that the rest of the code isn't run when fgetc() returns EOF:
while( (c = fgetc(myfile)) != EOF)

Edited by Ancient Dragon

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.