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);
putchar(c);
characterAmount++;
charactersInLine++;
if(c == ' ')
wordCount++;
if(c == '\n')
{
if(charactersInLine > longestLine)
longestLine = charactersInLine;
charactersInLine = 0;
lineCount++;
wordCount++;
}
}
Thanks for you time!
This is becoming one of the most common problems, heh.
You’re missing that
fgetc()returnsint, notchar. This is becauseEOFis not a valid character, so a larger type is needed. See this documentation, for instance.You’re also testing
cbefore assigning it for the first time, which basically makes your code rely on whatever happens to be in the uninitialized variable. This is a problem.Also, you should probably test for
EOFbefore counting.Further, it’s considered a bad idea to use magic numbers in code.
This:
can be written:
and this:
can be:
which are both clearer, in my opinion.