使用write()将整数列表写入文件

问题描述 投票:0回答:1

作为我必须将进程一起管道化的问题的一部分,我必须让一个进程简单地从标准输出中发送整数序列1,2 ...... 10000。我遇到的问题是我无法以任何形式或形式正常工作。

我一直在编写一个(非常)简单的程序来尝试不同的方法。当我直接写入stdout时,我得到一个10000个数字的无形列表。当我尝试将数字字符串写入文件时,文本编辑器在我尝试打开它时会冻结。该计划如下:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

int main(int argc, char* argv[]) {

    char *arg[]= {"/home/eric/Documents/pr3/test.txt"};
    int i;
    int fp = open(arg[0], O_WRONLY);
    char tmp[12]={0x0};
    for(i=1; i<=10000; i++){
        sprintf(tmp,"%11d", i);
        write(fp, &tmp, sizeof(tmp));
    }
} 

我不知道为什么会这样,并且非常感谢一些帮助。

谢谢。

c linux string
1个回答
2
投票

您可能有权限问题。默认情况下,open()会创建一个具有权限的文件,在查看文件时会出现问题。看看我对open()电话所做的更改。您每次都需要删除该文件。

使用sizeof()也不正确。您应该使用您使用sprintf()编写的字符串的长度。我更喜欢从sprintf()获取输出,但我相信strlen()会给你相同的数字。更改后,我可以在文本编辑器中打开文件。

我还添加了错误检查以确保您的文件是打开的。

也关闭你的文件。

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

int main(int argc, char* argv[]) {

    char *arg[]= {"/home/eric/Documents/pr3/test.txt"};
    int i;
    int fp = open(arg[0], O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
    if(fp<0){
    // do some error msg here
    }

    char tmp[12]={0x0};
    int size = 0;
    for(i=1; i<=10000; i++){
        size = sprintf(tmp,"%11d", i);
        write(fp, &tmp, size);
    }
    close(fp);
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.