views:

127

answers:

4

Hi

Why does this not compile? Cant see the error

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

int main(void)
{
    char *c;
    FILE *f = fopen("file.txt", "r");

    if(f == NULL) {
        printf("Could not open file");
    }

    while((c = fgetc(f)) != EOF) {
        if(strcmp(c, " ") == 0) {
            printf(" ");
        } else if(strcmp(c, ":") == 0) {
            printf(":");
        } else if(strcmp(c, "@") == 0) {
            printf("@");
        } else if(strcmp(c, "\n") == 0) {
            printf("\n");
        } else {
            printf("Not a valid char");
    }
}

}

+9  A: 

fgetc returns the char currently at the file pointer as an integer.

So char *c; should be int c;

and

if(strcmp(c, " ") == 0) {

should be

if(c == ' ') {

and similarly change other comparisons.

You can compact the comparisons as:

while((c = fgetc(f)) != EOF) {
    if(c == ' ' || c == ':' || c == '@' || c == '\n') {
        printf("%c",c);
    } else {
        printf("Not a valid char");
    }
}
codaddict
+1 because you defined the type of c as int and not char.
JeremyP
A: 

Because a char * is not a char.

The fgetc function returns a character, not a string. That means that your entire group of if statements is wrong too. You should be doing simple things like:

if( c == ' ' ) {
} else if( c == ':' ) {
} ...
Zan Lynx
fgetc returns an int actually.
JeremyP
A: 

As mentioned, fgetc returns an int not actually a string (So strcmp will fail). My personally preferred though not really any different method of char comparison is to use a switch, and since you have several printing out the input character you might have something like:

while( (c = fgetc(f)) != EOF ) {
  switch( c )
  {
    case ' ':
    case ':':
    case '@':
    case '\n':
      printf( "%c", c );
      break;
    default:
      printf( "Not a valid char" );
  }
}

I have found this to be the easiest way, especially when you know you'll want to expand on your conditions later. ( Say if you wanted to add: 'f', 'o', and 'r' )

Ian Lee
fgetc returns an int, not a char
William Pursell
A: 

Yes, fgetc() returns int, not char or char*. Why is this important? Because EOF is usually (always?) defined as -1. If fgetc() returns EOF into an 8 bit char, it will be represented as 0xFF. In some character sets this is a valid character. e.g. y-umlaut in ISO-8859-1. Thus using

char c; // << this is wrong, use int
while((c = fgetc(aFile)) == EOF)
{
     // stuff
}

you cannot distinguish between end of file and one of the characters that can legitimately appear in the stream.

JeremyP
char ? not int?
fahad
Why the down vote? The code sample was to demonstrate how **not** to do it. Please fully read the answer before down voting.
JeremyP