Function to write to specified file name

Hi everyone,

I'm trying to write a function that will write to a filename specified in the main function. The function should take the name argument as a constant character pointer to the specified name. I am having trouble figuring out how to do this and how to concatenate this name with the extension .txt. Would anyone be able to give me some advice?

(Don't worry about the other two arguments of the function... I have those figured out)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int main()
{
	const char *filename = "name";
	
	write(*filename, 5, 90);
}


void write(const char *filename, int N, int M)
{
	char *exten = ".txt";
	const char *fileNew = strcat(*filename, *exten);
	
	fstream inout;
	inout.open(*fileNew, ios::out);

    //and so on to output the file
}
Don't dereference the pointers when passing them to the functions. They want a pointer, so give them one.
Your compiler should at least have warned you!?
Oh yeah, it warned me... the function works when I write the filename directly into the write function. What I'm having difficulty with is creating a c string within the write function from the filename from the main function. It doesn't compile the way it is here, of course.
This won't work because filename
1. isn't mutable, and
2. wouldn't be long enough to take those additional 4 characters.

Solutions:
1. Use std::string (see cplusplus.com Reference) instead of char*.
2. Use malloc(3) (have a look at you man page section 3) to allocate a string containing enough characters. Or use new.
3. Use a local char array having enough elements.
string s = "my file.txt";
fstream inout;
inout.open(s.c_str(), ios::out);
out<< "blablabla<< endl;
out.close();


.c_str() also works with everything that wont take a regular string as well. like remove(), and the like.
Topic archived. No new replies allowed.