i am a beginner .can anyone just give me a code to make a txt file using c code,that will create txt file with name same as the value of int variable..

consider like if int x=10,then file name created will be 10.text

if x is assigned 45 then it will create file name as 45.txt

plzz help..i can't fig out how to do that,i am doing one project that processes input and store that data with the name inputed by user i.e. numbers

Edited by jimu: n/a

6 Years
Discussion Span
Last Post by jimu

i have the code ready, but i am not giving it now.
use sprintf function to create filename (as in number+".txt")

FILE * fopen(char * filename, char * mode);

to open the file.


I used a char array
char filename, and a char *extension = ".txt".

I used an unsigned int for the number. As the program looped around for another filename increment, the file_num++, of course.

iota() from ctype.h, was then used to put the number into the filename char array. Then I used strcat() from string.h, to add the .txt onto the end of the filename array. You need to include both ctype.h and string.h.

FILE *fp = fopen(filename, "wt");
if(fp==NULL) {
  printf("Error opening %s\n", filename);
  exit() or return;

If you don't have itoa(), check your help files for things like ltoa() or stroi, etc. You can "peel" off the digits from the number and put them into the string by hand, but it's much more work.

Post up your attempt and we'll get you sorted out.

Edit: For a small number of numbered files, only:

Char's are just numbers with a very small range, so you can also increment the filename char's, directly:
filename[3]++; //etc.

The problem with this, is you have to handle every bit of the arithmetic, yourself (changing a 9 to a 10, leaving the zero there, and incrementing the adjacent element of the array, by one). If you have many numbers, forget this and use the way above.

Edited by Adak: n/a


thanks for help...i'll just try and let u know

Edited by jimu: n/a

This question has already been answered. 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.