关于Linux C write函数的一些情况,麻烦解释一下哦!

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#define FILENAME "/home/test.txt"
#define FLAGS O_WRONLY | O_CREAT | O_TRUNC
#define MODE 0666
int main(void)
{
char buf1[ ]={"abcdefghij"};
char buf2[ ]={"1234567890"};
int fd;
int count;
const char *pathname=FILENAME;
if ((fd=open(pathname, FLAGS, MODE)==-1))
{
printf("error, open file failed!\n");
exit(1);
}
count=strlen(buf1);
if (write(fd, buf1, count)!=count)
{
printf("error, write file failed!\n");
exit(1);
}
if (lseek(fd, 50, SEEK_SET)==-1)
{
printf("error, lseek failed!\n");
exit(1);
}
count=strlen(buf2);
if (write(fd, buf2, count) != count)
{
printf("error, write file failed!\n");
exit(1);
}
return 0;
}
/*
gcc -o hole hole.c
./hole
ls /home/test.txt
od -c /home/test.txt
*/

求指点:为什么/home/test.txt文件总是为0字节,内容并没有写到文件中

MMTTMM
浏览 410回答 2
2回答

扬帆大鱼

好隐蔽的一个错误!! if ((fd=open(pathname, FLAGS, MODE)==-1)) 这句,括号的位置错误了应该是: if ( (fd=open(pathname, FLAGS, MODE))==-1)原写法,导致fd值为0,成了标准输入(终端)了,所以,lseek就会一直报错!

智慧大石

1.功能将数据写入已打开的文件内2.相关函数open,read,fcntl,close,lseek,sync,fsync,fwrite3.表头文件#include<unistd.h>4.定义函数ssize_t write (int fd,const void * buf,size_t count);5.函数说明write()会把参数buf所指的内存写入count个字节到参数fd所指的文件内。当然,文件读写位置也会随之移动。6.返回值如果顺利write()会返回实际写入的字节数。当有错误发生时则返回-1,错误代码存入errno中。7.错误代码EINTR 此调用被信号所中断。EAGAIN 当使用不可阻断I/O 时(O_NONBLOCK),若无数据可读取则返回此值。EBADF 参数fd非有效的文件描述词,或该文件已关闭。
打开App,查看更多内容
随时随地看视频慕课网APP