linux cプログラミングファイルIO
4261 ワード
記事の内容は
21日学通linux cプログラミング
主な関数:
開く:fopen fdopen freopen
閉じる:fclose
読み込みよみとり:getc fgets fread
書き込み:putc fputc fputs fwrite
読み取り文字
文字列の読み込み
書き込み文字
書き込み文字列
データの書き込み
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.
",file);
printf("errno:%d
",errno);
printf("ERR :%s
",strerror(errno));
return;
}
else
{
printf("%s was opened.
",file);
}
for(i=0;i<10;i++)
{
a=getc(fp);
if(a==EOF)
{
break;
}
printf("%c",a);
}
printf("
");
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.
",file);
printf("errno:%d
",errno);
printf("ERR :%s
",strerror(errno));
return;
}
else
{
printf("%s was opened.
",file);
}
fgets(a,5,fp);
printf("%s
",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.
",file);
printf("errno:%d
",errno);
printf("ERR :%s
",strerror(errno));
return;
}
else
{
printf("%s was opened.
",file);
}
i=fread(mystu,sizeof(struct stu),3,fp);
printf("%d students was read.
",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.
",file);
printf("errno:%d
",errno);
printf("ERR :%s
",strerror(errno));
return;
}
else
{
printf("%s was opened.
",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.
",file);
printf("errno:%d
",errno);
printf("ERR :%s
",strerror(errno));
return;
}
else
{
printf("%s was opened.
",file);
}
i=fputs(txt,fp);
{
printf("%d char was written.
",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.
",file);
printf("errno:%d
",errno);
printf("ERR :%s
",strerror(errno));
return;
}
else
{
printf("%s was opened.
",file);
}
i=fwrite(mystu,sizeof(mystu),3,fp);
printf("%d students was written.
",i);
close(fp);
}