|
Linux下C语言的文件(fputc,fgetc,fwrite,fread对文件读写操作)
//==================================
fputc 向文件写入字符
- #include <stdio.h>
- #include <stdlib.h>
- main()
- {
- FILE *fp;
- char ch;
- if((fp=fopen("test.txt","w"))==NULL)
- {
- printf("不能打开文件\n");
- exit(0);
- }
- while ((ch=getchar())!='\n')
- fputc( ch, fp );
- fclose(fp);
- }
复制代码
-------------
小提示:
fp=fopen("test.txt","w") ,把"w"改为 "a" 可以创建文件并且追加写入内容
exit(0); 需要包含 stdlib.h 头文件,才能使用
//============================================================
fgetc 读取字符
- #include <stdio.h>
- #include <stdlib.h>
- main( int argc, char *argv[] )
- {
- char ch;
- FILE *fp;
- int i;
- if((fp=fopen(argv[1],"r"))==NULL)
- {
- printf("不能打开文件\n");
- exit(0);
- }
- while ((ch=fgetc(fp))!=EOF)
- putchar(ch);
- fclose(fp);
- }
复制代码
文件结尾,通过判断 EOF
//==============================================================
fwrite 的使用
使数组或结构体等类型可以进行一次性读写
- #include <stdio.h>
- #include <stdlib.h>
- main()
- {
- FILE *fp1;
- int i;
- struct student{
- char name[10];
- int age;
- float score[2];
- char addr[15];
- }stu;
- if((fp1=fopen("test.txt","wb"))==NULL)
- {
- printf("不能打开文件");
- exit(0);
- }
- printf("请输入信息,姓名 年龄 分数1 分数2 地址:\n");
- for( i=0;i<2;i++)
- {
- scanf("%s %d %f %f %s",stu.name,&stu.age,&stu.score[0],&stu.score[1], stu.addr);
- fwrite(&stu,sizeof(stu),1,fp1);
- }
- fclose(fp1);
- }
复制代码
//===============================================================
fread 的使用
- #include <stdio.h>
- #include <stdlib.h>
- main()
- {
- FILE *fp1;
- int i;
- struct student{
- char name[10];
- int age;
- float score[2];
- char addr[15];
- }stu;
- if((fp1=fopen("test.txt","rb"))==NULL)
- {
- printf("不能打开文件");
- exit(0);
- }
- printf("读取文件的内容如下:\n");
- for (i=0;i<2;i++)
- {
- fread(&stu,sizeof(stu),1,fp1);
- printf("%s %d %7.2f %7.2f %s\n",stu.name,stu.age,stu.score[0],stu.score[1],stu.addr);
- }
- fclose(fp1);
- }
复制代码
//==========================================
fprintf , fscanf, putw , getw , rewind , fseek 函数
这些函数的话我就不演示了 ,
这些函数基本都一对来使用,例如 fputc 和 fgetc 一起来用
|
|