简体   繁体   中英

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?

  1. consult man 2 open to get the right arguments for open . It should be:

     open(argv[1], O_WRONLY | O_CREAT | O_TRUNC); 
  2. You should only write ad much as you actually have:

     write(archivo, environ[i], strlen(environ[i])); 
  3. 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();
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM