0

Im trying to make my program to either open or create a file if it does not exist, in "C://".

printf("Filename: ");
  scanf("%s",filename);
  FILE *fil;
  fil=fopen(filename,"a+");

This code opens or creates a file in the same folder as the program.


What i want is something like this:

printf("Filename: ");
  scanf("%s",filename);
  FILE *fil;
  fil=fopen("C://"+filename,"a+");

How do i write this ?

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

First, don't use scanf() because it won't take anything beyond the first space you type, consequently you can not enter a file name that includes spaces. You need to use fgets() for that. Next, you have to concantinate the two strings together.

char filename[260]; // max allows in MS-Windows path + filename
strcpy(filename,"c:/");
fgets(&filename[3], 257,stdin);
// now strip off the newline 
if( filename[strlen(filename)-1) == '\n')
    filename[strlen(filename)-1) = 0;
0

if you just want to use file name without space then use this

FILE *fp;
char filename[40];  // you can use max lenght 260

strcpy(filename,"c:/");

printf("\n Enter File Name:");

scanf("%s",&filename[3]);

fp=fopen(filename,"a+");
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.