Exciless
Exciless

Reputation: 1

How to write a c program to create a file?

I want to create a file by importing the file name from the user, please help

int file_name;
printf("Enter ID NUMBER : ");
scanf("%d",&file_name);
FILE *fin;
fin = fopen(&file_name , "w");

Upvotes: 0

Views: 70

Answers (1)

Achal
Achal

Reputation: 11921

Here

FILE *fin;
fin = fopen(&file_name , "w"); /* this is wrong, since &file_name is of int* type */

fopen() expects first argument of char* type but you have provided as of int* type which is wrong, and which has been reported by compiler correctly as

error: incompatible pointer types passing 'int *' to parameter of type 'const char *' [-Wincompatible-pointer-types]

if you could have compiled with flag like -Wall -Wpedantic -Werror. From the manual page of fopen()

FILE *fopen(const char *pathname, const char *mode);

Declare file_name as array of characters & store the name of file into it.

char file_name[1024]; /* take a char array to store file name */
/* @TODO : store actual file name into file_name array */
FILE *fin = fopen(file_name , "w");
if(fin == NULL) {
  /* @TODO : error handling */
}

Upvotes: 1

Related Questions