我编写了以下代码来模拟write()
中的C
系统调用。
程序执行时没有错误,但新内容不会写入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);
}
答案 0 :(得分:3)
你应该检查写入的返回值,看看perror发生了什么(例如),
无论如何你没有以正确的方式打电话
试
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
答案 1 :(得分:1)
打开文件时,需要指定打开的模式(读取或写入)。在您的公开呼叫中,您没有指定任何模式,并且您正在提供文件权限标记。有关更多信息,请参阅开放系统调用的手册页。
你可以在公开电话中试试这个
fd=open("myfile", O_WRONLY | O_CREAT, 0660);
检查您的写入调用的返回值,它失败了,因为您没有指定任何模式,并且您正在尝试将数据写入该文件。