-3

I was wondering if there is a way to append data to a file without using functions from standard I/O libraries (i.e. stdio.h). I though of doing something like this first:

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

int main() {
    int fd = open("test.txt", O_WRONLY | O_CREAT, 0700);
    ssize_t wr = write(fd, "hello world", sizeof("hello world");
}

But this only writes data to the file without appending it so instead repeatedly displaying "hello world", it only overwrites the previous data and displays it once. Can someone please help me out? Thanks

M.Ahmed
  • 11
  • 4

1 Answers1

-3

Try this:

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

int main() {
    int fd = open("test.txt", O_WRONLY | O_CREAT | O_APPEND, 0700);
    ssize_t wr = write(fd, "hello world", strlen("hello world");
    exit(0);
}
vy32
  • 28,461
  • 37
  • 122
  • 246
  • I treid doing exactly what you did but it still doesn't work. I then tried using lseek() to seek to the end of the file, but it still doesn't work. – M.Ahmed Feb 22 '18 at 00:25
  • note that your code doesn't even compile – Jean-François Fabre Feb 22 '18 at 00:40
  • @M.Ahmed your code doesn't compile, the answer code doesn't compile, and works fine after fixing the typo. This question & answer is just useless, broken, duplicate stuff – Jean-François Fabre Feb 22 '18 at 00:42
  • Not all combos of flags are valid. Maybe write-only is incompatible with append, (how can the file system find the end if it is not allowed to read the file?). – Martin James Feb 22 '18 at 00:48
  • 1
    So, that's both the OP and yourself that cannot count brackets:( – Martin James Feb 22 '18 at 00:55
  • Does anyone bother to close files? A compliant C will close files opened with fopen(), but if you bypass that, you may end up with buffered output discarded by the OS. – Martin James Feb 22 '18 at 01:00
  • @MartinJames in that case, example is using unbuffered output. But yes, those youngsters nowadays... – Jean-François Fabre Feb 22 '18 at 01:42
  • @Jean-FrançoisFabre there is no guarantee of unbuffered output - just because you cannot see it in the C source or in the crt stdio buffer does not mean that the OS has not buffered it, and may discard that buffer from its I/O system before it is written if the process that owns/issued it is terminated:( – Martin James Feb 22 '18 at 09:23
  • If OP wants an atomic operation, then the OP asked the wrong question. The OP should have asked how to get a lock on a file. – vy32 Feb 22 '18 at 22:08