1

I want to write to a file, that is inside a folder in the current working directory, with the file name being the number value that is passed to the function.

void record_data(number[]) { FILE *fptr; fptr = fopen("./folder/number", "w"); } 

I'm unable to do so in this way (it names the file as number).

How can I do this properly?

3
  • Do you mean record_data( int number )? Commented Jan 19, 2016 at 19:46
  • This is invalid (number[]) in C. Commented Jan 19, 2016 at 19:48
  • If you mean void record_data(const char number[]) (so you pass the number as a string), then you need to concatenate the ./folder/ string with the number (snprintf() into a local variable) and pass the concatenated value to fopen(). If you pass the number as an int (void record_data(int number)), then you still need to use snprintf() to format the file name into a local variable and pass that to fopen(), but the format will be different. Commented Jan 19, 2016 at 19:48

1 Answer 1

8

Assuming you meant int number as opposed to your number[] which is not valid C.

You can use sprintf(), or preferably snprintf():

void record_data(int number) { char str[255]; //Large enough buffer. snprintf(str, sizeof(str), "./folder/%d", number); FILE *fptr; fptr = fopen(str, "w"); } 

And consider calling fclose() on your FILE * when you're done using it.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.