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;
}`
5
  • Hint: Please, add a debug statement std::cout << "sizeof text: " << sizeof text << '\n';. I'm afraid sizeof(text) does not what you expect. Commented Mar 28, 2019 at 9:35
  • 1
    As @Scheff suspected, sizeof(text) will return you the size of a char pointer. Commented Mar 28, 2019 at 9: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. Commented Mar 28, 2019 at 9: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. Commented Mar 28, 2019 at 9:39
  • If you enter ”hi there”, argc will be 4, with ”hi” as argv[2] and ”there” as argv[3]. Commented Mar 28, 2019 at 11:18

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.