Search code examples
c++cposixfile-descriptor

How to write a struct to a file using write() function?


I want to write a struct object to a file using the write() function. It has to be that function.

My input from terminal is: ./main.c output.dat John Doe 45

When I run the program and open the output.dat there are bunch of letters that don't make sense. Please help me.

The output I want in my output.dat file is: John Doe 45

My code:

struct Person{
  char* name;
  char* lastName;
  char* age;
};

int main(int argc, char** argv){

    struct Person human;
    /* get the argument values and store them into char*         */
    char* fileName = argv[1];
    char* name = argv[2];
    char* lastName = argv[3];
    char* age = argv[4];

    /* set the values of human object */
    human.name = name;
    human.lastName = lastName;
    human.age = age;

    /* open the file */
    int file = 0;
    file = open(fileName, O_RDWR); /* I want to have read&write set! */
    write(file, &human, sizeof(human));
    close(file);


    return 0;
}

Solution

  • Thanks to all, I sloved it like this. Although it is not ideal it gets the job done :) :

    struct Person{
       char name[20];
       char lastName[20];
       char age[20];
    };
    
    int main(int argc, char** argv){
    
       struct Person human;
       /* get the argument values and store them into char*         */
       char* fileName = argv[1];
       char* name = argv[2];
       char* lastName = argv[3];
       char* age = argv[4];
    
       sprintf(human.name,name);
       sprintf(human.lastName,lastName);
       sprintf(human.age,age);
    
       /* open the file */
       int file = 0;
       file = open(fileName, O_RDWR); /* I want to have read&write set! */
       write(file, &human, sizeof(human));
       close(file);
    
    
       return 0;
    }