【发布时间】:2015-06-28 21:23:03
【问题描述】:
#include<sys/stat.h>
#include<stdio.h>
#include<fcntl.h>
#include<sys/types.h>
int main()
{
int n,i=0;
int f1,f2;
char c,strin[100];
f1=open("data",O_RDWR|O_CREAT|O_TRUNC);
while((c=getchar())!='\n')
{
strin[i++]=c;
}
strin[i]='\0';
write(f1,strin,i);
close(f1);
f2=open("data",O_RDONLY);
read(f2,strin,0);
printf("\n%s\n",strin);
close(f2);
return 0;
}
这段代码在某些机器上运行良好,而在其他机器上打印出垃圾,如何让它在所有机器上正确运行?
【问题讨论】:
-
请先检查
open()的返回值是否成功。 -
即使我省略了文件访问部分,即只填充字符串然后再次打印,我仍然得到相同的结果
-
您尝试过格式化 i/o 吗?
-
"man -S2 read" 说:DESCRIPTION read() 尝试从文件描述符 fd 中读取 count 个字节到缓冲区,从 buf 开始。如果 count 为零,则 read() 返回零并且没有其他结果。如果 count 大于 SSIZE_MAX,则结果未指定。但我尝试了此代码和 read(),同样使用 count==0,返回读取字节数!!!
-
我告诉你,我上面指出的奇怪情况是由于我没有清理缓冲区!