0

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;
}`
  • Hint: Please, add a debug statement `std::cout << "sizeof text: " << sizeof text << '\n';`. I'm afraid `sizeof(text)` does not what you expect. – Scheff's Cat Mar 28 '19 at 09:35
  • 1
    As @Scheff suspected, `sizeof(text)` will return you the size of a `char` pointer. – Korni Mar 28 '19 at 09:37
  • Spoiler alert: Please note, `text` is of type `char*`. Hence, `sizeof text` returns the size of the pointer - 4 byte on a 32 bit platform or 8 byte on a 64 bit. – Scheff's Cat Mar 28 '19 at 09:37
  • 1
    In the specific case of `char*` pointing to a C string (with 0 terminator), there is a C function `strlen()` dedicated for this. – Scheff's Cat Mar 28 '19 at 09:39
  • If you enter ”hi there”, `argc` will be 4, with ”hi” as `argv[2]` and ”there” as `argv[3]`. – molbdnilo Mar 28 '19 at 11:18

1 Answers1

1

Use strlen(text) in<string.h> instead of sizeof(text) to determine the length of the string, sizeof(text) will return you the size of a pointer, which is always the same.

Korni
  • 464
  • 2
  • 10