gpt4 book ai didi

c - Linux系统调用c语言中的write()不起作用?

转载 作者:行者123 更新时间:2023-11-30 21:18:49 25 4
gpt4 key购买 nike

我编写了以下代码:

它应该接受一个文件名并创建它并写入它。什么都没发生。我不明白为什么。我尝试搜索并看到类似的例子应该可以正常工作。如果重要的话,我将 VirtualBox 与 Xubuntu 一起使用。

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <time.h>
#include <assert.h>
#include <errno.h>
#include <string.h>

#define SIZE_4KB 4096
#define FILE_SIZE 16777216



/*Generate a random string*/
char* randomStr(int length)
{
int i = -1;
char *result;
result = (char *)malloc(length);
while(i++ < length)
{
*(result+i) = (random() % 23) + 67;
if(i%SIZE_4KB)
*(result+i) = '\0';
}
return result;
}

void writeFile(int fd, char* data, int len, int rate)
{
int i = 0;
len--;
printf("Writing...\n");
printf("to file %d :", fd);
while(i < len)
{
write(fd, data, rate);
i += rate;
}
}

int main(int argc, char** argv)
{
int i = -1, fd;
char *rndStr;
char *filePath;
assert (argc == 2);
filePath = argv[1];
rndStr = randomStr(FILE_SIZE);
printf("The file %s was not found\n", filePath);
fd = open(filePath, O_CREAT, O_WRONLY);
writeFile(fd, rndStr, FILE_SIZE, SIZE_4KB);
return 0;
}

最佳答案

open 调用是错误的。通过使用 OR 组合参数来指定多个标志。而且,当您创建文件时,第三个参数应该是您希望文件拥有的权限。所以你的 open 调用应该是这样的:

fd = open(filePath, O_CREAT | O_WRONLY, 0666);
if (fd < 0)
Handle error…

您应该始终测试系统调用和库函数的返回值,以查看是否发生错误。

关于c - Linux系统调用c语言中的write()不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13298271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com