码迷,mamicode.com
首页 > 编程语言 > 详细

Linux下的C语言读写练习(读取键盘输入)

时间:2017-12-17 11:07:44      阅读:527      评论:0      收藏:0      [点我收藏+]

标签:img   就是   time   types.h   文件操作   get   读写   最大的   习题   

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;

}

技术分享图片

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

 

Linux下的C语言读写练习(读取键盘输入)

标签:img   就是   time   types.h   文件操作   get   读写   最大的   习题   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!