gpt4 book ai didi

无法在 C 中模拟 write() 系统调用

转载 作者:行者123 更新时间:2023-11-30 18:32:02 24 4
gpt4 key购买 nike

我编写了以下代码来模拟C中的write()系统调用。程序执行没有错误,但新内容没有写入 myfile

问题是什么?

#include<stdio.h>

int main(int ac, char* av[])
{
int fd;
int i = 1;
char *sep = "";

if(ac < 1)
{
printf("Insuff arguments\n");
exit(1);
}
if((fd = open("myfile", 0660)) == -1)
{
printf("Cannot open file");
exit(1);
}
while(i<ac)
{
write(fd, av[i], strlen(av[i]));
write(fd, sep, strlen(sep));
i++;
}
close (fd);
}

最佳答案

您应该检查 write 的返回值并查看 perror 发生了什么(例如),

无论如何,您没有以正确的方式调用 open

尝试

  if ((fd=open("myfile", O_WRONLY | O_CREAT, 0660))==-1)
{
printf("Cannot open file");
exit(1);
}
while(i<ac)
{
write(fd,av[i],strlen(av[i])); //check the return value of write
write(fd,sep,strlen(sep));
perror("write");
i++;
}
close (fd);

并包含 unistd.h fcntl.h

关于无法在 C 中模拟 write() 系统调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17542637/

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