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

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)

Thanks alot. Fixed alot of problems for me.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.