首页 > 编程语言 > 详细

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

时间:2017-12-17 10:24:32      阅读:299      评论:0      收藏:0      [点我收藏+]

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语言读写练习(读取键盘输入)

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!