Ulrik
Ulrik

Reputation: 1141

Rewriting file using O_TRUNC

I need to read the contents of a binary file into a buffer, perform an operation on that buffer, than to rewrite the contents of that same file with the output buffer.

#include <fcntl.h>
#define BUFFSIZE 1024
char  in[BUFFSIZE],
     out[BUFFSIZE];

void main(char argc, char **argv)
{
    int file = open(argv[1], O_RDONLY);
    int size = read(file, in, BUFFSIZE);
    hash(in, out, size);
    close(file);
    file = open(argv[1], O_WRONLY, O_TRUNC);
    write(file, out, size);
    close(file);
}

If I open the file using O_RDWR, and then use write(), my output buffer is appended to the end of the file. If I close and re-open the file with O_TRUNC, it does not truncate it - output buffer is smaller than the input, so the remnant of the old content can be seen at the end of the file. On the other hand, using O_WRONLY makes a file to which I do not have permission to write. I know how to do this using fopen() and fprintf(), but I would like to avoid that, and, if possible avoid unnecessary closing (use some sort of rewind).

Upvotes: 0

Views: 836

Answers (1)

DrC
DrC

Reputation: 7698

Change your second open call to

file = open(argv[1], O_WRONLY | O_TRUNC);

and I think you will get what you want.

BTW, you should check return results from things like open, read, write and close.

Upvotes: 1

Related Questions