Question

Using freopen I want to write to a file with same name as the file i am reading in the program but with differnt extension ?

suppose i am reading file abc.jpg I want to write in file abc.txt in the same program .

I am giving the initials of the files as argument but getting compilation error. I am reading multiple files and writing to multiple files.

  freopen ( "abc" + ".txt" , "w" , stdout ) ;

  error : cannot convert parameter 1 from 'std:string' to 'char *'    
Was it helpful?

Solution

The + operator does not do string concatenation with two string literals. In C++ (going by your tags), you can use std::string to do the concatenation:

#include <string>

...

std::string baseFilename("abc");
std::string newFilename(baseFilename + ".txt");

freopen(newFilename.c_str(), "w", file);

The std::string class does support concatenation via +. Note that we're using c_str() because the freopen() function still takes a C-style string pointer (const char *).

OTHER TIPS

As written in question it is C not C++.

#include <cstdio>
#include <string>
FILE* fp;

...

freopen ( (std::string("abc")+std::string(".txt")).c_str() , "w" , fp ) ;

as function takes const char* and file pointer FILE*.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top