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,221
  • 8
  • 38
  • 44
JAN
  • 20,056
  • 54
  • 170
  • 290

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
  • 44,735
  • 12
  • 114
  • 137
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
  • 587,191
  • 41
  • 1,025
  • 1,442
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
  • 103,426
  • 11
  • 122
  • 196
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);