Back to where I was, now I'm learning how to use fgetc properly. Does fgetc read in a character? If so I can't find my error in my code and I'm getting a a segfault. Can you help fix it and explain why it doesn't work? Thanks


//declare variables for file input/output
FILE *infile;
char infile_name[15];
FILE *outfile;
char outfile_name[15];

char *buffer;
char fchar;

//declare variables for binary search tree

int main(void) {
        printf("p2a     ");
        scanf("%s,%s \n", infile_name,outfile_name); //reads in file names
        printf("Opening file %s ...\n", infile_name);
        infile = fopen(infile_name, "r"); //open file stream
        fchar = fgetc(infile); //read a character

        printf("The first char is %s\n", fchar); //print a character
10 Years
Discussion Span
Last Post by Aia

Probably because you're outputting the 'char' as a 'char array'.

printf("The first char is %s\n", fchar);

Try changing %s to %c .

Some other things...

- fchar should be an integer. This way, you guarantee that it can hold an EOF character when the end of the input buffer is reached.

- Make sure that infile is a valid pointer before you try to read from it! This could cause unexpected results if the filename the user entered doesn't exist or can't be opened.


>I'm learning how to use fgetc properly
fgetc reads a character from the stream passed and return that character. The catch is that
character needs an int, so fchar needs to be of type int.
...but that's not your problem.

printf("The first char is %s\n", fchar); //print a character

print a character? That's not what you are telling to do with %s, that's for strings.
...but that's not your problem.

infile = fopen(infile_name, "r"); //open file stream

Always check that the file was opened or accessed.

if( infile == NULL )
     <error of some kind>

...still not your given problem

>I'm getting a a segfault.
Now that's a problem. It means your program has tried to accessed wrong memory space.

scanf("%s,%s \n", infile_name,outfile_name); //reads in file names

That , and the \n is not correct. But then, scanf is not the correct function for reading input from user.
fgets() is.

This topic has been dead for over six months. 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.