Arian Motamedi
Arian Motamedi

Reputation: 7413

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

1) I have a struct and need to write it to a file using the write() system call, NOT fwrite(). Is this possible?

2) After writing the structure to the file, I need to read another file, and write it to end of the file the structure is now written in.

Any help would be appreciated.

Upvotes: 2

Views: 11139

Answers (4)

tomahh
tomahh

Reputation: 13651

this will write your structure to a file.

int fd = open(file, O_WRONLY);
struct my_struct a;

write(output, &a, sizeof(struct my_struct));

For the other file, simply open it, read it's content in a loop, and write it to the previous.

int fd2 = open(otherfile, O_RDONLY);
int readret;
char buf[4096];

while ((readret = read(fd2, buf, sizeof(buf) != 0) {
  write(fd, buf, readret); 
}

remember to test every write/read result, (as mention in the comment), and handle those errors.

Upvotes: 5

overlox
overlox

Reputation: 822

write and fwrite just work the same way the only difference is that write uses a file destriptor (fd), where fwrite uses a FILE *

Upvotes: 0

paddy
paddy

Reputation: 63451

If you are talking about writing your structure in binary, then yes. The function usage as described in K&R is:

int n_written = write( int fd, char *buf, int n );

So you would have:

struct mystruct s;
write( fd, (char*)&s, sizeof(s) );

If you wish to serialize the struct in text, you will want to use sprintf or similar to construct a formatted string and then write that out to the file.

Now, you want to read in another file and write that out to the file you just dumped the struct into. Just use read and write to move chunks of data at a time. A reasonable practise is to move chunks that are a multiple of the disk sector size (traditionally 512 bytes, but these days you might want to take something like 4096 for generality).

Upvotes: 1

Assuming you have declared

struct somestruct_st mydata;

you can write it with

ssize_t cnt = write (yourfd, &mydata, sizeof(mydata));
if (cnt != sizeof(mydata)) {
   // handle that case
}

Upvotes: 0

Related Questions