0

is there any option to generate an output text file as same as the input file name?

in C i got the file name using:

gets(file_name);

and open it through the:

f1=fopen(file_name,"r");

comment.how do i open the file without entering the format type? for example for file100.txt i'd like to enter file100 to read the file.

and any option to get the output file as same name as the input file?

hmjd
  • 120,187
  • 20
  • 207
  • 252

3 Answers3

0

You can use

snprintf(new_filename, sizeof new_filename, "%s.%d", File_name, int_val);
unwind
  • 391,730
  • 64
  • 469
  • 606
Manik Sidana
  • 2,005
  • 2
  • 18
  • 29
0

For your problem with the file name, you can use e.g. sprintf:

char full_file_name[256];
sprintf(full_file_name, "%s.txt", file_name);

This is not recommended without some validation of the entered file name of course.

For your other problem, from the documentation of fopen:

r+     Open for reading and writing.  The stream is positioned at the beginning
       of the file.

w+     Open for reading and writing.  The file is created if it does not exist,
       otherwise it  is  truncated.
       The stream is positioned at the beginning of the file.

a+     Open for reading and appending (writing at end of file).  The file is
       created if it does  not  exist.
       The  initial file position for reading is at the beginning of the file,
       but output is always appended to the end of the file.
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • It is likely that, rather than being able to use those fopen options, the OP needs to write to an output file and then replace the input file with it. On linux it's common to have a command called 'into' that buffers all of its input before writing any of it to stdout, so one can do things like `cat foo bar | into foo` – Jim Balter Jun 19 '12 at 11:47
0

for creating output file with the same name, simply save your output content into some string. Then, close the file and open it again with write mode("w"). And then, write the content and close the file again.

Hgeg
  • 545
  • 6
  • 19
  • By "string" you apparently mean "buffer". If the program dies after opening the file with "w" mode but before it can write out the buffer, the content of the file will be lost. It's safer to write to a temp file and then rename it to the name of the input file (the rename is an atomic operation in Linux). – Jim Balter Jun 19 '12 at 11:51