文件相关调用接口:
一.fopen,fwrite,fread的使用
1. fwrite:myfile文件中的信息
# include<stdio.h>
# include<string.h>
int main()
{
FILE *fp=fopen("myfile","w");
if(!fp){
printf("fopen error!\n");
}
const char *msg="hello world!\n";
int count=5;
while(count--){
fwrite(msg,strlen(msg),1,fp);
}
fclose(fp);
return 0;
}
2. fread:
# include<stdio.h>
# include<string.h>
int main()
{
FILE *fp=fopen("myfile","r");
if(!fp){
printf("fopen error!\n");
}
char buf[1024];
const char *msg="hello world!\n";
while(1){
ssize_t s=fread(buf,1,strlen(msg),fp);
if(s>0){
buf[s]=0;
printf("%s",buf);
}
if(feof(fp)){
break;
}
}
fclose(fp);
return 0;
}
3..输出信息到显示器的三种不同方法
# include<stdio.h>
# include<string.h>
int main()
{
const char *msg="hello fwrite\n";
fwrite(msg,strlen(msg),1,stdout);
printf("hello printf\n");
fprintf(stdout,"hello fprintf\n");
return 0;
}
二.系统文件IO
3. 写文件write:myfile文件中的信息
# include<sys/types.h>
# include<sys/stat.h>
# include<fcntl.h>
# include<unistd.h>
# include<string.h>
int main()
{
umask(0);
int fd=open("myfile",O_WRONLY|O_CREAT,0644);
if(fd<0){
perror("open");
return 1;
}
int count=5;
const char *msg="hello world\n";
int len=strlen(msg);
while(count--){
write(fd,msg,len);
}
close(fd);
return 0
}
.2、读文件read
# include<sys/types.h>
# include<sys/stat.h>
# include<fcntl.h>
# include<unistd.h>
# include<string.h>
# include<stdio.h>
int main()
{
int fd=open("myfile",O_RDONLY);
if(fd<0){
perror("open");
return 1;
}
const char *msg="hello world\n";
char buf[1024];
while(1){
ssize_t s=read(fd,buf,strlen(msg));
if(s>0){
printf("%s",buf);
}
else{
break;
}
}
close(fd);
return 0;
}
三、文件描述符
1.
# include<stdio.h>
# include<sys/types.h>
# include<sys/stat.h>
# include<fcntl.h>
# include<string.h>
int main()
{
char buf[1024];
ssize_t s=read(0,buf,sizeof(buf));
if(s>0){
buf[s]=0;
write(1,buf,strlen(buf));
write(2,buf,strlen(buf));
}
return 0;
}
2.(1)
# include<stdio.h>
# include<sys/types.h>
# include<sys/stat.h>
# include<fcntl.h>
# include<string.h>
int main()
{
int fd=open("myfile",O_RDONLY);
if(fd<0){
perror("open");
return 1;
}
printf("fd:%d\n",fd);
close(fd);
return 0;
}
输出fd为3
(2)关闭或者2
# include<stdio.h>
# include<sys/types.h>
# include<sys/stat.h>
# include<fcntl.h>
# include<string.h>
int main()
{
close(0);
//close(2);
int fd=open("myfile",O_RDONLY);
if(fd<0){
perror("open");
return 1;
}
printf("fd:%d\n",fd);
close(fd);
return 0;
}
结果为输出fd为0或者2
结论:文件描述符的分配规则为:在file_struct数组中,找到当前没有被使用的最后一个下标,作为新的文件描述符。
3.重定向
# include<stdio.h>
# include<sys/types.h>
# include<sys/stat.h>
# include<fcntl.h>
# include<string.h>
int main()
{
close(1);
int fd=open("myfile",O_RDONLY);
if(fd<0){
perror("open");
return 1;
}
printf("fd:%d\n",fd);
fflush(stdout);
close(fd);
return 0;
}
# include<string.h>
{
const char *msg0="hello printf\n";
const char *msg1="hello fwrite\n";
const char *msg2="hello write\n";
printf("%s",msg0);
fwrite(msg1,strlen(msg0),1,stdout);
write(1,msg2,strlen(msg2));
fork();
return 0;
}