CREATING A FILE OFSTREAM help

closed account (ivDwAqkS)
when I try to create a file on the desktop, typing "file.txt" it prints me out that the file was not opened, I don't know why... it should create the file or maybe override it, can someone help me how can I create or re-write a file just giving the complete path name?

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
26
27
28
29
30
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

#define MAX 1000
int main(){
    char filename[MAX + 1];
    char address[MAX + 1];


    cout << "Enter the file name: ";
    cin.getline(filename, MAX);
    strcpy(address, "c:\\users\\username\\desktop\\");
    //strcpy(address, "c:\\desktop\\"); bad location
    strcat(address, filename);

    ofstream filee(address);

    if(!filee){
        cout << address << " could not be opened."<<endl;
        return -1;
    }
    cout << address << " was opened and overrided." << endl;
    filee << "hi?, ";
    filee << "hellow :p"<<endl;
    filee.close();

    return 0;
}
Last edited on
Make sure the filepath you have given it exists. In unix systems, to specify an absolute pathname, you usually start the name with a '/' symbol. I'm not sure what it is on windows. But make sure you are specifying the full path to your program. Or you could run your program on the desktop and just open the file there
why are you using char for filename and not string?

just curious, i dont code like you.
Last edited on
closed account (ivDwAqkS)
Sky3 i am using a book where it gives me an example with char but the example is only with the file name and i wanted to know why it didnt work with the complete path name, and yes i could use string also.
Your code is not wrong. But your path is.

Change it to:
1
2
3
4
//cout << "Enter the file name: ";
//cin.getline(filename, MAX);
strcpy(address, "C:\\desktop\\test.txt");
//strcat(address, filename); 


Then run it, for testing purposes.

Last edited on
closed account (ivDwAqkS)
Bufige, it still not working
Most likely either the directory doesn't exist or you do not have write permissions for the directory.
closed account (ivDwAqkS)
Naraku9333 but when i call the file by the name it work, it only happens with the path name, and i cant figure out what it is.
Open up a command prompt and change directory until the you are on desktop. Then type this command: echo %cd%

The output of that command should tell you if you are using the correct pathname
closed account (ivDwAqkS)
thank you the path name was wrong, it was c:\users\username\desktop, thank you Smac89 :)
Last edited on
Topic archived. No new replies allowed.