linux 下C语言文件读取问题

具体程序如下:

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

int main()
{
char buf[]="abcdefghijklmnopqrstuvwxyz\n";
int fp,total,num;
toal=sizeof(buf);
if (fp=open("22.txt",O_WRONLY|O_CREAT|O_APPEND,0666)<0)
{
printf("file open fail");
exit(1);
}

while(num=write(fp,buf,sizeof(buf))!=total)
{
total=total-num;
}
close(fp);
}

程序运行时,只生成了目标文件,但是没有把数据写入文件,请问是神噩梦问题~~求指导

问题在于if判断:

if (fp=open("22.txt",O_WRONLY|O_CREAT|O_APPEND,0666)<0)

=优先级最低,所以,文件打开成功返回一个文件标识符,小于0不成立,所以,返回0,fp的值就是0,下面write写的时候写到0(标准输入)上面了,经过我测试,确实是写到屏幕上来了,有可能相当于键盘输入的,但是在VC下测试,不会输出到屏幕,所以,文件里面是空的。

修改如下:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
char buf[]="abcdefghijklmnopqrstuvwxyz\n";
int fp,total,num;
total=sizeof(buf);
printf("size =%d\n", total);
if ((fp=open("22.txt",O_WRONLY|O_CREAT|O_APPEND,0666))<0)
{
printf("file open fail");
exit(1);
}
while(num=write(fp,buf,sizeof(buf))!=total)
{
total=total-num;
}
close(fp);
}

运行截图:

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-05-03
write没有定义buf的大小,你去看看write的第三个参数,不是结束条件,而是block size追问

那应该怎么修改?
数据没有写入文件,而是输出在了屏幕上。。。

第2个回答  2013-05-03
把toal=sizeof(buf)这句改成toal=strlen(buf)
sizeof(buf)和strlen(buf)算出来的不一样的..
相似回答