简体   繁体   English

C语言中的open()和write()函数

[英]open() and write() functions in C

I'm trying to write in a .txt file the content of the variable environ . 我正在尝试在.txt文件中写入变量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 . 咨询man 2 open以获得正确的论据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. write并不能保证您提交的所有内容都会被写入。

Ideally you should look for the far more programmer friendly stdio calls fopen and fwrite . 理想情况下,您应该寻找对程序员更友好的stdio调用fopenfwrite

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(). “ rw”不适用于open(),适用于fopen()。

open(argv[1], O_WRONLY);

I think is the minimum required for writing to a file using open 我认为使用open写入文件的最低要求

EDIT: I found a link http://pubs.opengroup.org/onlinepubs/009696899/functions/open.html 编辑:我找到了一个链接http://pubs.opengroup.org/onlinepubs/009696899/functions/open.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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