how to read a file name like 01JUN2009_tsea_360x181.dat

Recommended Answers

All 3 Replies

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?

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.

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(). ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.