C system calls open / read / write / close problem.
        Posted  
        
            by Andrei Ciobanu
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Andrei Ciobanu
        
        
        
        Published on 2010-04-03T19:57:17Z
        Indexed on 
            2010/04/03
            20:03 UTC
        
        
        Read the original article
        Hit count: 327
        
c
|system-calls
Hello, given the following code (it's supposed to write "hellowolrd" in a "helloworld" file, and then read the text):
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#define FNAME "helloworld"
int main(){ 
    int filedes, nbytes;
    char buf[128];
    /* Creates a file */
    if((filedes=open(FNAME, O_CREAT | O_EXCL | O_WRONLY | O_APPEND, 
        S_IRUSR | S_IWUSR)) == -1){
            write(2, "Error1\n", 7);
    }
    /* Writes hellow world to file */
    if(write(filedes, FNAME, 10) != 10)
        write(2, "Error2\n", 7);
    /* Close file */
    close(filedes);
    if((filedes = open(FNAME, O_RDONLY))==-1)
        write(2, "Error3\n", 7);
    /* Prints file contents on screen */    
    if((nbytes=read(filedes, buf, 128)) == -1)
        write(2, "Error4\n", 7);
    if(write(1, buf, nbytes) != nbytes)
        write(2, "Error5\n", 7);
    /* Close rile afte read */
    close(filedes); 
    return (0);
}
The first time i run the program, the output is:
helloworld
After that every time I to run the program, the output is:
Error1
Error2
helloworld
I don't understand why the text isn't appended, as I've specified the O_APPEND file. Is it because I've included O_CREAT ? It the file is already created, shouldn't O_CREAT be ignored ?
© Stack Overflow or respective owner