2

In order to write to a new file , I do the following :

// some code 
...

 pfd[i][0] = open(argv[j+1],O_CREAT|O_WRONLY,0600);

Questions :

  1. Is there a difference between using open or fopen ?

  2. How can I use open for opening an existing file in append mode ?

ani627
  • 5,578
  • 8
  • 39
  • 45
JAN
  • 21,236
  • 66
  • 181
  • 318

4 Answers4

2
  1. open is for POSIX systems. It is not portable to other system. fopen is part of C standard, so it will work on all C implementation. I am ignoring the difference that open returns a file descriptor where fopen returns a FILE *.

  2. Use O_APPEND to open for append mode.

taskinoor
  • 45,586
  • 12
  • 116
  • 142
1
  1. The difference is that open is a non-portable, POSIX function and fopen is portable, standard C function.
  2. Specify O_APPEND when calling open to use append mode.
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
1

Use O_APPEND

quote from open() description in POSIX documentation

O_APPEND
If set, the file offset shall be set to the end of the file prior to each write.

pmg
  • 106,608
  • 13
  • 126
  • 198
1

1) Yes. There is a diference: Buffered or non-buffered I/O.
open() gives to you a RAW file handle (there isn´t a buffer between your program and the file in the file system).

fopen() gives to you the permission to work with files in stream buffer mode. For example, you can read/write data line-by-line (\0).

You can see the big diference when work with functions like: fprintf(), fscanf(), fgets(), fflush().

ps: fopen() isn´t better than open(). They are different things. Some times you need stream buffer (fopen), some times you need work byte-by-byte (open).

Here is a good reference about stream: http://www.cs.cf.ac.uk/Dave/C/node18.html#SECTION001820000000000000000

2) To open in append mode, add O_APPEND flag:

open(argv[j+1],O_CREAT|O_APPEND|O_WRONLY,0600);