How To Append To File in C, using Open in O_APPEND Mode on linux?

Well, I just tried your program and have an idea of what is going wrong.

Basically, it does work, but with a glitch. When you first write "thy fall" into the file, you use a char array of 4096 bytes, and you write the entire array into the file. Which means you're writing "thy fall" followed by 4088 characters of random nothing. Later, when you append you're appending at the 4097th position onwards. This is probably not what you intended to do.

If you simply cat the file you create, you will see the expected output "thy fall, dude". But when you read it entirely in your code, you are only reading 4096 characters. Hence, the ", dude" part is never read, which is why your program never outputs it.

My solution, you need to change your array size. And when reading, read in chunks of say 100 or 1000, until you hit EOF (read will return -1).


The number of bytes you are trying to write is not correct,

char buf[BUFFSIZE] = {'t', 'h', 'y', ' ', 'f', 'a', 'l', 'l'};
size_t n = sizeof(buf);
if(write (fd, buf, n) < 0){

instead of that you should do

char buf[BUFFSIZE] = {'t', 'h', 'y', ' ', 'f', 'a', 'l', 'l', '\0'};
size_t n = strlen(buf); //use strlen 
if(write (fd, buf, n) < 0){

Similarly, do this for other write and reads as well. If you are not writing '\0' in the file to terminate string, you will not get it when you read data from file.

While reading you should try until entire file is read, ie. you get EOF.


There is just a small mistake, you need to change the sizeof function to strlen because the sizeof function will return the size of the array but the strlen function just return the length of the string stored in the array!