I'm trying to write out data that the user entered into argv[2]. I have to use write() system call (unix)
for Example I enter "hi there" but "hi th" is written out into the file instead of the whole text.
#include <iostream>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
using namespace std;
using std::cout;
using std::endl;
int main(int argc, char *argv[])
{
int fd, fileWrite;
char *file = argv[1]; //file to be create
char *text = argv[2]; //text stored here
fd = open(file, O_WRONLY | O_APPEND | O_CREAT);
//write message from command line
fileWrite = write(fd, text, sizeof(text));
fileWrite = write(fd, "\n", 1);
if(fileWrite == -1){
perror("fileWrite");
}
//close file
close(fd);
return 0;
}`
std::cout << "sizeof text: " << sizeof text << '\n';. I'm afraidsizeof(text)does not what you expect.sizeof(text)will return you the size of acharpointer.textis of typechar*. Hence,sizeof textreturns the size of the pointer - 4 byte on a 32 bit platform or 8 byte on a 64 bit.char*pointing to a C string (with 0 terminator), there is a C functionstrlen()dedicated for this.argcwill be 4, with ”hi” asargv[2]and ”there” asargv[3].