Q: open() and write() functions in C I'm trying to write in a .txt file the content of the variable environ.
int archivo = open(argv[1], "rw");
int i=0;
while(environ[i]!=NULL){
    write(archivo, environ[i], 1024);
    i++;
}

The file is created but no content is added. Does anyone know why?

A: *

*consult man 2 open to get the right arguments for open. It should be:
open(argv[1], O_WRONLY | O_CREAT | O_TRUNC);


*You should only write ad much as you actually have:
write(archivo, environ[i], strlen(environ[i]));


*You have to make sure that what you wrote actually left the buffer:
size_t string_length = strlen(environ[i]);
size_t wrote = 0;
while (wrote < string_length) {
    size_t bytes_wrote = write(archivo, environ[i] + wrote, string_length - wrote);
    if (bytes_wrote >= 0)
        wrote += bytes_wrote;
    else {
        perror("write");
        abort();
    }
}

write does not guarantee that all that you submit will be written.
Ideally you should look for the far more programmer friendly stdio calls fopen and fwrite.
FILE * fp = fopen(argv[1], "w");

// loop i
if (!fwrite(environ[i], strlen(environ[i]), 1, fp)) {
    perror("fwrite");
    abort();
}


A: I believe you've got to change your flags for opening a file.  "rw" isn't for open(), it is for fopen().
open(argv[1], O_WRONLY);

I think is the minimum required for writing to a file using open
EDIT: I found a link http://pubs.opengroup.org/onlinepubs/009696899/functions/open.html
