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;
}
具體步驟如下

操作文件讀寫的時候一定要注意指針指向的位置,使用lseek來固定指針的位置,否則將導致無法正確的讀出數據。
