Mahmoud Emam
Mahmoud Emam

Reputation: 1527

fopen error with the file name

What's the error in this code? I am just new in C language.

#define FNAME         "c:\\users\\mahmud\\desktop\\CDs\\"
#define READ_BIN      "rb"

static void open_existing_list()
{
char name[11];
FILE *fptr;

printf("\nPlease enter list name: ");
fflush(stdin);
scanf("%s", name);

fptr = fopen(FNAME name ".dat", READ_BIN);
}

This code is used to read the file name from the user, then open this File.

 D:\Mhmud\Mahmud\Programming\C\Videos\VTC - C  Programming\Course_Project\main.c In function `open_existing_list': 
75 D:\Mhmud\Mahmud\Programming\C\Videos\VTC - C  Programming\Course_Project\main.c syntax error before "name" 
 D:\Mhmud\Mahmud\Programming\C\Videos\VTC - C  Programming\Course_Project\Makefile.win [Build Error]  [main.o] Error 1 

Upvotes: 0

Views: 1311

Answers (3)

user529758
user529758

Reputation:

#define FNAME         "c:\\users\\mahmud\\desktop\\CDs\\
                                                        ^
You're missing the ending quotation mark here: ---------+

(Edit: it seems it was just a copy-paste typo.)

Add the missing quote and also fix this:

fptr = fopen(FNAME name ".dat", READ_BIN);

This only works for string literals, since the concatenation occurs at compile time. You want to write something like this:

char fname[512];
snprintf(fname, sizeof(fname), "%s%s.dat", FNAME, name);
fptr = fopen(fname, READ_BIN);

Upvotes: 4

cnicutar
cnicutar

Reputation: 182639

fptr = fopen(FNAME name ".dat", READ_BIN);

You can only concatenate string literals like that, and name isn't a string literal. Use sprintf or strcat to build up your path.

char path[LENGTH];
snprintf(path, sizeof(path), "%s%s.dat", FNAME, name);

Upvotes: 2

unwind
unwind

Reputation: 399823

You can't concatenate a string literal (the FNAME macro expansion) with a variable.

To concatenate strings involving variables, you need to do more work. Look up the strcat() function, or snprintf(). The latter is better.

Upvotes: 3

Related Questions