4
Contributors
3
Replies
5
Views
5 Years
Discussion Span
Last Post by Narue
0

Depends on many things like:
what's in the file?
where the file is?
is it protected?
is it encrypted?
is is broken?
is it locked?

0

Filenames are char's, so fgets() is always one of the better choices:

fgets(charArrayName, sizeof(charArrayName), filePointerName);

It adds a newline onto the end of the string, but it can be readily removed if you don't want it there:

int len = strlen(charArrayName);
if(charArrayName[len-1]== '\n')
   charArrayName[len-1]='\0';  //overwrite the newline char by shortening the string

scanf() can be used in this case, but it's a lot more work, because of the '.' and filename extension after it.

0

scanf() can be used in this case, but it's a lot more work, because of the '.' and filename extension after it.

Eh? I see no reason why scanf() would be harder for those reasons. The %s specifier uses whitespace as a delimiter:

char filename[50];

if (scanf("%49s", filename) == 1) {
    /* Yay! */
}
else {
    /* Boo! */
}

However, modern operating systems allow embedded whitespace, and that's a good reason to avoid the %s specifier. Though you could use a scanset to read the full line:

char filename[50];

if (scanf("%49[^\n]", filename) == 1) {
    /* Yay! */
}
else {
    /* Boo! */
}

That said, I'd still recommend fgets(). ;)

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.