我是想在a.txt文件中通过write()写入字符串,然后将该字符串通过read()放在数组buf1中,然后打印buf1,但是发现完全打印不出来任何东西。或者是会打印出乱码: 代码如下:
int main()
{
int openflag = O_RDWR;
int fd;
int numwirte, numread, len_s1;
char buf1[20];
fd= open("a.txt", openflag);
if(fd==-1)
perror("open");
char *s1 = "a new string\0";
len_s1 = strlen(s1);
numwirte = write(fd, s1, len_s1);
numread = read(fd, buf1, len_s1);
printf("numwrite:%d\n",numwirte);
printf("numread:%d\n",numread);
printf("buf1[0]:%c\n", buf1[0]);
printf("the string in buf1: %s\n", buf1);
close(fd);
return 0;
}
程序运行结果如图:
求教各位大神,为何buf1没打印任何东西呢
写完文件后,文件指针移动到文件末尾了,所以你这时候读是读不到东西的,需要把文件指针重置回文件开头再读