Saiyan
Saiyan

Reputation: 197

C - write() input data to file

The user inputs, for 2 students, the name, ID, date of birth, gender and marital status. I should then write each input individually to a file. This is my code.

#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>

int main()
{
    int fd, i;
    char name[20], id[10], dob[10], gender[7], status[10];
    fd = open("lab45.txt", O_WRONLY|O_CREAT, S_IRWXU);
    for (i = 1; i < 3; i = i + 1)
    {
        printf("\n\nStudent %d", i);
        printf("\n-Name: ");
        scanf(" %[^\n]", name);
        printf("\n-ID: ");
        scanf("%s", id);
        printf("\n-Date of birth: ");
        scanf("%s", dob);
        printf("\n-Gender: ");
        scanf("%s", gender);
        printf("\n-Marital status: ");
        scanf("%s", status);
        write(fd, &name, 20);
        write(fd, &id, 10);
        write(fd, &dob, 10);
        write(fd, &gender, 7);
        write(fd, &status, 10);
    }
    close(fd);
}

I input the following:

Student 1

-Name: John Smith

-ID: JS3019

-Date of birth: 14/10/90

-Gender: male

-Marital status: single

Student 2

-Name: Jane Doe

-ID: JD0192

-Date of birth: 13/12/99

-Gender: female

-Marital status: married

This is what I see in the text file afterwards.

John Smith\00\00\00\00\00\00\A0@\00JS3019\00\00\C0\F414/10/90\00\00male\00\00\00single\00\00\EDJane Doe\00h\00\00\00\00\00\00\A0@\00JD0192\00\00\C0\F413/12/99\00\00female\00married\00\ED

Is this normal or there is something wrong in my code?

Upvotes: 1

Views: 615

Answers (1)

Carl Norum
Carl Norum

Reputation: 225162

The problem you see is the result of writing the entire arrays to the file rather than just the parts containing data. You can either:

  1. Use fprintf to print string data to the file rather than using write:

    FILE *f = fdopen(fd, "w");
    fprintf(f, "%s", name);
    
  2. Change the length value you pass to write to include only the used data:

    write(fd, &name, strlen(name));
    

Upvotes: 1

Related Questions