Linux下的C语言读写练习(一)(读取键盘输入输出通过文件的方式)

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
",m);
m=lseek(fd1,-m,SEEK_CUR);

printf("%d
",m);
read(fd1,buf,10);

printf("we get output string :%s",buf);
close(fd);
close(fd1);
return 0;

}

具体步骤如下

操作文件读写的时候一定要注意指针指向的位置,使用lseek来固定指针的位置,否则将导致无法正确的读出数据。

原文地址:https://www.cnblogs.com/a986771570/p/8051353.html