文章内容参考自
21天学通linux c编程
主要函数:
打开: fopen fdopen freopen
关闭: fclose
读取: getc fgets fread
写入: putc fputc fputs fwrite
读取字符
#include <stdio.h>
#include <errno.h>
main()
{
FILE * fp;
extern int errno;
char file[]="/root/a1.txt";
fp=fopen(file,"r");
int i;
char a;
if(fp==NULL)
{
printf("cant't open file %s.\n",file);
printf("errno:%d\n",errno);
printf("ERR :%s\n",strerror(errno));
return;
}
else
{
printf("%s was opened.\n",file);
}
for(i=0;i<10;i++)
{
a=getc(fp);
if(a==EOF)
{
break;
}
printf("%c",a);
}
printf("\n");
fclose(fp);
}
读取字符串
#include <stdio.h>
#include <errno.h>
main()
{
FILE * fp;
extern int errno;
char file[]="/root/a1.txt";
fp=fopen(file,"r");
int i;
char a[5];
if(fp==NULL)
{
printf("cant't open file %s.\n",file);
printf("errno:%d\n",errno);
printf("ERR :%s\n",strerror(errno));
return;
}
else
{
printf("%s was opened.\n",file);
}
fgets(a,5,fp);
printf("%s\n",a);
fclose(fp);
}
读取数据
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
struct stu
{
char name[10];
int age;
};
main()
{
struct stu mystu[3];
FILE * fp;
extern int errno;
char file[]="/root/a1.txt";
int i,j;
fp=fopen(file,"a+");
if(fp==NULL)
{
printf("cant't open file %s.\n",file);
printf("errno:%d\n",errno);
printf("ERR :%s\n",strerror(errno));
return;
}
else
{
printf("%s was opened.\n",file);
}
i=fread(mystu,sizeof(struct stu),3,fp);
printf("%d students was read.\n",i);
close(fp);
}
写入字符
#include <stdio.h>
#include <errno.h>
main()
{
FILE * fp;
extern int errno;
char file[]="/root/a1.txt";
char txt[5]="hello";
int i=0;
fp=fopen(file,"a+");
if(fp==NULL)
{
printf("cant't open file %s.\n",file);
printf("errno:%d\n",errno);
printf("ERR :%s\n",strerror(errno));
return;
}
else
{
printf("%s was opened.\n",file);
}
for(i=0;i<5;i++)
{
putc(txt[i],fp);
printf("%c",txt[i]);
}
fclose(fp);
}
写入字符串
#include <stdio.h>
#include <errno.h>
main()
{
FILE * fp;
extern int errno;
char file[]="/root/a1.txt";
char *txt="hello";
int i;
fp=fopen(file,"a+");
if(fp==NULL)
{
printf("cant't open file %s.\n",file);
printf("errno:%d\n",errno);
printf("ERR :%s\n",strerror(errno));
return;
}
else
{
printf("%s was opened.\n",file);
}
i=fputs(txt,fp);
{
printf("%d char was written.\n",i);
}
close(fp);
}
写入数据
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
struct stu
{
char name[10];
int age;
};
main()
{
struct stu mystu[3];
FILE * fp;
extern int errno;
char file[]="/root/a1.txt";
int i;
strcpy(mystu[0].name,"Jim");
mystu[0].age=14;
strcpy(mystu[0].name,"Jam");
mystu[1].age=14;
strcpy(mystu[0].name,"Lily");
mystu[2].age=19;
fp=fopen(file,"a+");
if(fp==NULL)
{
printf("cant't open file %s.\n",file);
printf("errno:%d\n",errno);
printf("ERR :%s\n",strerror(errno));
return;
}
else
{
printf("%s was opened.\n",file);
}
i=fwrite(mystu,sizeof(mystu),3,fp);
printf("%d students was written.\n",i);
close(fp);
}