I have input files like this
a.iup
b.iup
c.iup.......

i have these input files in a variable called fname;
like this

char *fname="c:\\iupfiles\\a.iup";
every time i will get file name in this variable. But how to concatenate the variable with some other name like as follows in output file name.

in a loop i will get one file at one time. I have write the output into file for each input file as
a_res.txt
b_res.txt
c_res.txt...

like this. How to do this..

Dani AI

Generated

Good quick solution from and well done on getting it to work. A few practical improvements worth keeping in mind when forming an output name from an input filename:

  • Use the last path separator and the last dot (not the first) so names like "my.file.iup" yield "my.file_res.txt" or extract the true base.
  • Avoid unbounded strcpy/strcat; prefer snprintf/memcpy or sized functions to prevent buffer overruns.
  • If you read names with fgets, strip the trailing newline. Always check pointers returned by strrchr/strchr before using them.

A compact, safe pattern in C is: extract the filename portion by finding the last '\' or '/', find the last dot with strrchr to get the extension start (if any), copy the base into a bounded buffer, then build the final name with snprintf. This handles paths, files without extensions, and names with multiple dots.

Notes: on Windows you can also use _splitpath/_splitpath_s; on POSIX basename helps. For long or unknown lengths use dynamic allocation or PATH_MAX. Always validate buffers and check return values when opening/writing the output file.

References: see the snprintf documentation () and strrchr behavior (strrchr).

Recommended Answers

All 2 Replies

you can use either sprintf() or strcat() to format the output file name. Example:

char outname[255];
char inputname[255];
char* ptr;

printf("Enter a file name\n");
fgets(inputname,sizeof(inputname),stdin);
strcpy(outname, inputname);
// truncate the extension
ptr = strchr(outname,'.');
if(ptr != NULL)
   *ptr = '\0';
// now add new filename
strcat(outname,"_res.txt");

Thnaks. Its working fine

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.