Frage

I am writing using CodeBlocks, GCC and using C language. The code I have is as follows:

char word[50];
FILE *fn;
fn = open("word.txt", "rb");
if(fn == NULL) perror("File not opened");
while(!feof(fn))
{
    fscanf(fn, "%s", word);
}

The text file has only one word in it (at present that is "batman"). I have tried various versions of this code including the following:

char* word;
char = malloc(50);
FILE *fn;
fn = open("word.txt", "rb");
if(fn == NULL) perror("File not opened");
while(!feof(fn))
{
    fscanf(fn, "%s", &word);
}

I honestly don't know why (and why this should be SO difficult) but the error that CodeBlocks is giving me is the dreaded SIGSEV segmentation fault at the feof line. When I didn't do the while loop the fscanf would throw a Segmentation fault. Please help! I don't often work in C and I remember why now. Even the most simple of things can be SO difficult. Thanks in advance.

UPDATE: I have actually got this to work (the top one) by changing the open line to:

fn = fopen("C://Temp//word.txt", "rb");

How can this work with relative paths?

War es hilfreich?

Lösung

Change

fn = open("word.txt", "rb");

to

fn = fopen("word.txt", "rb");

open returns an int, which is not a FILE*. feof and fscanf expect a FILE* not an int as its first parameter, that's the reason why feof() and, if you remove it, fscanf() segfaults.

And as others already noted, change fscanf(fn, "%s", &word) to fscanf(fn, "%s", word).

Andere Tipps

Assuming that word is a char * (your code is not clear), this instruction will bring you problems:

fscanf(fn, "%s", &word);

Just change it by:

fscanf(fn, "%s", word);

Also, I suggest you to use the fopen function instead of open, since fscanf works with descriptors provided by fopen.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top