programmer0 programmer0 - 25 days ago 25
C++ Question

write in the file with Linux

How do I write my input in the file?
Here is my code

#include <iostream>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
int main(int argc,char *argv[]){
int fd;
int x;
int *y;
fd=open(argv[1], O_WRONLY|O_CREAT , S_IREAD|S_IWRITE);
cin>>x;
*y=x;
write(fd,y, 4);
}

return 0;
}


Maybe there is something wrong with permissions that i give to the file because when i try to open the file from directory it gives this

"There was a problem opening the file “/home/ubuntu/Desktop/file.txt”. The file you opened has some invalid characters. If you continue editing this file you could corrupt this document.
You can also choose another character encoding and try again."

Answer

According to file name and the fact you are opening result file in a text editor, you suppose to write into text file. On C++ you should use std::ofstream instead of open/write:

    cin>>x;
    std::ofstream fd( argv[1] );
    fd << x << std::endl;

that would write number as a text. What you are currently doing is dumping int as binary blob, which text editor does not expect to get.

Note: you have to check that argc>1 so argv[1] does have value, otherwise you would get UB. You may check that file opened properly, though in simple app you can ignore that, as writing in such case would not have bad effects (I mean crash or etc).

Comments