Edit PHP File using C++

I am trying to get my c++ program to take user input from a form and then the c++ program takes it in and prints that input to a file that is located in the same folder it is. For some reason it won't write to the file. Here's the c++ code:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <fstream>
#include <string>
#include <limits>
using namespace std;

int main()
{
	string temp = getenv("QUERY_STRING");
	getline(cin,temp);
	fstream file("results.php",ios::out | ios::in | ios::binary);
	if(file.is_open())
	{
		file << "this is a test" << endl;
		file << temp << endl;
	}
	else
	{
		cout << "Content-type: text/html\n\n";
		cout << "error" << endl;
	}
	file.close();
	cin.ignore( numeric_limits<streamsize>::max(), '\n' );
	return 0;
}
1. It might write the file, but since you didn't provide a path not at the location you expect.
2. Due to ios::in the file must exists otherwise it will not be opened
you can try something like this...

1
2
3
4
5
6
7
8
9
10
11
12
if(file.is_open())
{
....
}
else
{
    file.open("results.php",ios::in|ios::out|ios::binary|ios::trunc);
    if(file.is_open())
    {....}
    else
    {cout << "Error opening file";}
}
Topic archived. No new replies allowed.