I’m a relatively decent Java programmer, but completely new to C. Thus some of these functions, pointers, etc are giving me some trouble…
I’m trying to create an archive file (I’m basically re-writing the ar sys call). I can fstat the files I want, store the necessary information into a struct I’ve defined. But now comes my trouble. I want to write the struct to the archive file. So I was thinking I could use sprintf() to put my struct into a buffer and then just write the buffer.
sprintf(stat_buffer, "%s", file_struct);
write(fd, stat_buffer, 60);
This doesn’t appear to work. I can tell the size of the archive file is increasing by the desired 60 bytes, but if I cat the file, it prints nonsense.
Also, trying to write the actual contents of the file isn’t working either…
while (iosize = read(fd2, text_buffer, 512) > 0) {
write(fd, text_buffer, iosize);
if (iosize == -1) {
perror("read");
exit(1);
}
}
I’m sure this is a relatively easy fix, just curious as to what it is!
Thanks!
%sis used to print string. So sprint will stop when it will meet a\0character.Instead, you could directly write your structure to your file.
write(fd, &file_struct, sizeof(filestruct));but you wont be able to read it with a cat call. You still can, from another unarchiver program, read the file content and store it to a structureread(fd, &filestruct, sizeof(filestruct));This system is not perfect anyways, because it will store the structure using your computer endianess and wont be portable. If you want to do it right, check out the ar file format specification.