C语言练习题:
1.从键盘读取10个字符,然后显示这10个字符(需要使用read和write函数)
2.写入5个字符到一个文本文件中
问题1.C语言一旦涉及到文件操作的问题,其实最大的问题就是指针的问题。由于在写完之后要考虑到指针依然在文件末尾,需要手动的去将指针归位
#include<stdio.h> #include<unistd.h> #include<fcntl.h> #include<stdlib.h> #include<string.h> #include<time.h> #include<sys/types.h> int main() { int fd,fd1,fd2,n,m,i,len; char c; char buff[10]; char buf[10]; fd=open("./test1.txt",O_RDWR|O_CREAT,755); fd1=open("./test2.txt",O_RDWR|O_TRUNC|O_CREAT,755); n=write(fd,"hello",5); printf("please input string:"); scanf("%s",buff); len=strlen(buff); if(len>10) { perror("the string is error please restart"); } m=write(fd1,buff,len); printf("%d\n",m); m=lseek(fd1,-m,SEEK_CUR); printf("%d\n",m); read(fd1,buf,10); printf("we get output string :%s",buf); close(fd); close(fd1); return 0; }
操作文件读写的时候一定要注意指针指向的位置,否则将导致无法正确的读出数据