一、目录
一、文件的基本操作
《1》fgetc , fputc 按字符读写文件
《2》fgets , fputs 按行读写文件
《3》fread , fwrite 按照块来读写文件
《4》按格式化读写文件
二、文件控制api
二、具体实现
一、文件的基本操作
《1》fgetc , fputc 按字符读写文件
<1>必备知识
fopen(char* filename , char* type );//打开文件
int fputc(int ch, FILE * stream);//按字符方式写文件
int fgetc(FILE* stream);//按字符方式读文件
feop( FILE * stream );//判断文件是否到达末尾
//r+在文件首追加
//a+在文件尾追加
<2>实例
《1》只读
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
int i=0;
FILE *fp=NULL;
char* filename="C:/传智课程操练/1.txt";
fp=fopen(filename,"r");//"r"只读
if(fp==NULL)
{
printf("func fopen() err: \n");
return;
}
while(!feof(fp))
{
char tmp=fgetc( fp );
printf("%c",tmp);
}
fclose(fp);
system("pause");
}
《2》在文件尾追加
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
int i=0;
FILE *fp=NULL;
char* filename="C:/传智课程操练/1.txt";
char array[]="abccccccccccccccccccccc";
fp=fopen(filename,"a+");//在文件尾追加语句
if(fp==NULL)
{
printf("func fopen() err: \n");
return;
}
for(i=0;i<strlen(array);i++)
{
fputc(array[i],fp);
}
fclose(fp);
system("pause");
}
(1)原文件1.txt
(2)运行程序结果
(3)系统提示是否修改
(4)修改后的1.txt
《3》在文件首追加
fp=fopen(filename,"r+");//在文件首追加语句
《2》fgets , fputs 按行读写文件
(2.1.1)文件正常读取测试:
/*
《1》题目:文件按行读写
《2》涉及知识:读写函数原型 :
char* fgets(char* str,int n,FILE *fpln );
str在主调函数中分配空间, 在被调函数中使用,
n必须为正整数,
表示从文件中读出的字符数不超过n-1个字符存入到str中,
并在末尾追加'\0';
如果函数正常执行,读取文件正常,则返回指向str字符串的指针,
否则返回NULL;
int fputs(const char* str, FILE* fpout);
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
int i=0;
FILE *fp=NULL;
char str[100];
char* filename="C:/传智课程操练/1.txt";
fp=fopen(filename,"r");//以只读的方式打开文件
if(fp==NULL)
{
printf("func fopen() err: \n");
return;
}
while(!feof(fp))
{
char*tmp=fgets( str, 100, fp );
if( tmp != NULL )
{
printf("%s",str);//输出并打印到屏幕上
}
}
fclose(fp);
system("pause");
}
(2.1.2)文件非正常执行测试
char*tmp=fgets( str, 0, fp );
//当n=0时,失败,只要系统检测到n=0,那么fgets函数就不再执行
(2.2.1)往文件中按照行的方式来写入字符串
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
int i=0;
FILE *fp=NULL;
char str[]="abcd";
char strlen=0;
char* filename="C:/传智课程操练/1.txt";
fp=fopen(filename,"a+");
if(fp==NULL)
{
printf("func fopen() err: \n");
return;
}
if(!feof(fp))//切忌这里不是循环,否则会循环向文件中写入字符串,导致系统崩溃
{
int tmp=fputs( str, fp );//注意这里申请的tmp是int型的,不是char*
}
fclose(fp);
system("pause");
}
(2.2.2)实验结果:
《3》fread , fwrite 按照块来读写文件
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define SIZE 5;
typedef struct _student
{
char name[10];
int num;
int age;
char addr[15];
}Student;
int main01()
{
int i;
FILE * fp=NULL;
Student student[5];
for(i=0;i<5;i++)
{
memset(&student[i],0,sizeof(Student));
}
if((fp=fopen("C:/传智课程操练/student.data","wb"))==NULL)
{
printf("不能打开文件\n");
return ;
}
for( i = 0;i < 5; i++)
{
sprintf(student[i].name,"name %d",i+1);
}
for( i = 0;i < 5; i++)
{
if(fwrite(&student[i],sizeof(Student),1,fp)!=1);
{
printf("文件写入错误\n");
}
fclose(fp);
}
return 0;
}
void display()
{
int i;
FILE * fp=NULL;
Student student[5];
for(i=0;i<5;i++)
{
memset(&student[i],0,sizeof(Student));
}
if((fp=fopen("C:/传智课程操练/student.data","rb"))==NULL)
{
printf("不能打开文件\n");
return ;
}
for( i = 0;i < 5; i++)
{
fread ( &student[i],sizeof(Student),1,fp) ;
printf("%-10s %4d %4d %-15s\n",student[i].name,student[i].num,
student[i].age,student[i].addr);
}
fclose(fp);
}
void main()
{
main01();
display();
system("pause");
}
1>以二进制写入形式创建文档,
2>未初始化数组产生的文档
3>初始化过后产生的文档
for(i=0;i<5;i++)
{//初始化语句部分
memset(&student[i],0,sizeof(Student));
}
4>读文档,并打印到屏幕上
《4》按格式化读写文件
二、文件配置api
// cfg_op.h
#ifndef _INC_CFG_OP_H
#define _INC_CFG_OP_H
#ifdef __cplusplus
extern "C" {
#endif
int GetCfgItem(char *pFileName /*in*/, char *pKey /*in*/, char * pValue/*in out*/, int * pValueLen /*out*/);
int WriteCfgItem(char *pFileName /*in*/, char *pItemName /*in*/, char *pItemValue/*in*/, int itemValueLen /*in*/);
//int CfgItem_Init(void *pHandle, int iType);
//int GetCfgItem(void *pHandle /*in*/, char *pKey /*in*/, char * pValue/*in out*/, int * pValueLen /*out*/);
//int WriteCfgItem(void *pFileName /*in*/, char *pItemName /*in*/, char *pItemValue/*in*/, int itemValueLen /*in*/);
//int CfgItem_Destory(void *pHandle);
#ifdef __cplusplus
}
#endif
#endif
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
int GetCfgItem(char *pFileName /*in*/, char *pKey /*in*/, char * pValue/*in out*/, int * pValueLen /*out*/);
int WriteCfgItem(char *pFileName /*in*/, char *pItemName /*in*/, char *pItemValue/*in*/, int itemValueLen /*in*/);
//实现流程
//打开文件
//按照行的方式 循环读文件
//解析每一行,若匹配key关键字,在进行value值的提取
//提取value值需要 1去除前后空格 1级指针典型应用
#define LineMaxLen 2048
#define KeyMaxLen 64
int GetCfgItem(char *pFileName /*in*/, char *pKey /*in*/, char * pValue/*in out*/, int * pValueLen /*out*/)
{
int rv = 0;
FILE *fp = NULL;
char lineBuf[LineMaxLen];
char *pTmp = NULL, *pBegin = NULL, *pEnd = NULL;
if (pFileName==NULL || pKey==NULL || pValue==NULL || pValueLen==NULL)
{
rv = -1;
printf("GetCfgItem() err. param err \n");
goto End;
}
fp = fopen(pFileName, "r");
if (fp == NULL)
{
rv = -2;
printf("fopen() err. \n");
goto End;
}
while (!feof(fp))
{
//读每一行
memset(lineBuf, 0, sizeof(lineBuf));
pTmp = fgets(lineBuf, LineMaxLen, fp);
if (pTmp == NULL)
{
break;
}
//不含=, 非配置项
pTmp = strchr(lineBuf, '=');
if (pTmp == NULL)
{
continue;
}
//key是否在本行
pTmp = strstr(lineBuf, pKey);
if (pTmp == NULL)
{
continue;
}
//调整到=右边,取value准备
pTmp = strchr(lineBuf, '=');
if (pTmp == NULL)
{
continue;
}
pTmp = pTmp + 1;
//获取value 起点
while (1)
{
if (*pTmp == ' ')
{
pTmp ++ ;
}
else
{
pBegin = pTmp;
if (*pBegin == '\n')
{
//没有配置value
printf("配置项:%s 没有配置value \n", pKey);
goto End;
}
break;
}
}
//获取valude结束点
while (1)
{
if ((*pTmp == ' ' || *pTmp == '\n'))
{
break;
}
else
{
pTmp ++;
}
}
pEnd = pTmp;
//赋值
*pValueLen = pEnd-pBegin;
memcpy(pValue, pBegin, pEnd-pBegin);
break;
}
End:
if (fp != NULL)
{
fclose(fp);
}
return rv;
}
//实现流程
//循环读每一行,检查key配置项是否存在 若存在修改对应value值
//若不存在,在文件末尾 添加 "key = value"
//难点:如何修改文件流中的值
int SetCfgItem(char *pFileName /*in*/, char *pKey /*in*/, char * pValue/*in*/, int ValueLen /*in*/)
{
int rv = 0, iTag = 0, length = 0;
FILE *fp = NULL;
char lineBuf[LineMaxLen];
char *pTmp = NULL, *pBegin = NULL, *pEnd = NULL;
char filebuf[1024*8] = {0};
if (pFileName==NULL || pKey==NULL || pValue==NULL)
{
rv = -1;
printf("SetCfgItem() err. param err \n");
goto End;
}
fp = fopen(pFileName, "r+");
if (fp == NULL)
{
rv = -2;
printf("fopen() err. \n");
//goto End;
}
if (fp == NULL)
{
fp = fopen(pFileName, "w+t");
if (fp == NULL)
{
rv = -3;
printf("fopen() err. \n");
goto End;
}
}
fseek(fp, 0L, SEEK_END);
//获取文件长度;
length = ftell(fp);
fseek(fp, 0L, SEEK_SET);
if (length > 1024*8)
{
rv = -3;
printf("文件超过1024*8, nunsupport");
goto End;
}
while (!feof(fp))
{
//读每一行
memset(lineBuf, 0, sizeof(lineBuf));
pTmp = fgets(lineBuf, LineMaxLen, fp);
if (pTmp == NULL)
{
break;
}
//key关键字是否在本行
pTmp = strstr(lineBuf, pKey);
if (pTmp == NULL)
{
strcat(filebuf, lineBuf);
continue;
}
else
{
sprintf(lineBuf, "%s = %s\n", pKey, pValue);
strcat(filebuf, lineBuf);
//若存在key
iTag = 1;
}
}
//若不存在 追加
if (iTag == 0)
{
fprintf(fp, "%s = %s\n", pKey, pValue);
}
else //若存在
{
if (fp != NULL)
{
fclose(fp);
fp = NULL; //避免野指针
}
fp = fopen(pFileName, "w+t");
if (fp == NULL)
{
rv = -4;
printf("fopen() err. \n");
goto End;
}
fputs(filebuf, fp);
//fwrite(filebuf, sizeof(char), strlen(filebuf), fp);
}
End:
if (fp != NULL)
{
fclose(fp);
}
return rv;
}
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "cfg_op.h"
#define DB_sid "oracle_sid"
#define DB_User "appuser"
#define DB_PassWord "appuser"
#define CFG_FILENAME "c:/cfg.ini"
void main_menu()
{
printf("\n1 Test SetCfgItem(测试设置配置文件) ");
printf("\n2 Test GetCfgItem(测试读取配置文件) ");
printf("\n0 exit(0) (程序退出) ");
printf("\nplease enter your choice:[1/2/0]: ");
return;
}
int Test_SetCfgItem()
{
int rv = 0;
int choice = 0;
char key[1024] ;
char value[1024];
memset(key, 0, sizeof(key));
memset(value, 0, sizeof(value));
printf("\nplease enter key:");
scanf("%s", key);
printf("\nplease enter value:");
scanf("%s", value);
rv = SetCfgItem(CFG_FILENAME, key, value, strlen(value));
if (rv != 0)
{
printf("SetCfgItem() err: %d \n", rv);
goto End;
}
/*
rv = GetCfgItem(CFG_FILENAME, DB_sid, value2, &value2Len);
if (rv != 0)
{
printf("SetCfgItem() err: %d \n", rv);
goto End;
}
//比较长度
if (valuelen != value2Len)
{
printf("(valuelen != value2Len) err\n");
goto End;
}
//比较内容
if (memcmp(value, value2, value2Len) != 0)
{
printf("(memcmp(value, value2, value2Len)) err\n");
goto End;
}
*/
printf("读写配置项绿灯测试通过\n");
End:
return rv;
}
int Test_GetCfgItem()
{
int rv = 0;
int choice = 0;
char key[1024] ;
char value[1024];
int valueLen = 1024;
memset(key, 0, sizeof(key));
memset(value, 0, sizeof(value));
printf("\nplease enter key:");
scanf("%s", key);
//printf("\nplease enter value:");
//scanf("%s", value);
rv = GetCfgItem(CFG_FILENAME, key, value, &valueLen);
if (rv != 0)
{
printf("SetCfgItem() err: %d \n", rv);
goto End;
}
printf("\n%s = %s", key, value);
printf("\n读写配置项绿灯测试通过\n");
End:
return rv;
}
/*
int Test_GetCfgItem()
{
int rv = 0;
int choice = 0;
char *value = "orcl";
int valuelen = strlen(value);
char value2[100];
int value2Len = 100;
memset(value2, 0, sizeof(value2));
rv = SetCfgItem(CFG_FILENAME, DB_sid, value, valuelen);
if (rv != 0)
{
printf("SetCfgItem() err: %d \n", rv);
goto End;
}
rv = GetCfgItem(CFG_FILENAME, DB_sid, value2, &value2Len);
if (rv != 0)
{
printf("SetCfgItem() err: %d \n", rv);
goto End;
}
//比较长度
if (valuelen != value2Len)
{
printf("(valuelen != value2Len) err\n");
goto End;
}
//比较内容
if (memcmp(value, value2, value2Len) != 0)
{
printf("(memcmp(value, value2, value2Len)) err\n");
goto End;
}
printf("读写配置项绿灯测试通过\n");
End:
return rv;
}
*/
int main()
{
int rv = 0;
int choice = 0;
for(;;)
{
main_menu();
scanf("%d", &choice);
switch (choice)
{
case 1:
Test_SetCfgItem(); break;
case 2:
Test_GetCfgItem(); break;
case 0:
exit(0);
default:
exit(0);
}
}
End:
return rv;
getchar();
}
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "cfg_op.h"
#define DB_sid "oracle_sid"
#define DB_User "appuser"
#define DB_PassWord "appuser"
#define CFG_FILENAME "c:/cfg.ini"
void main_menu()
{
printf("\n1 Test SetCfgItem(测试设置配置文件) ");
printf("\n2 Test GetCfgItem(测试读取配置文件) ");
printf("\n0 exit(0) (程序退出) ");
printf("\nplease enter your choice:[1/2/0]: ");
return;
}
int Test_SetCfgItem()
{
int rv = 0;
int choice = 0;
char key[1024] ;
char value[1024];
memset(key, 0, sizeof(key));
memset(value, 0, sizeof(value));
printf("\nplease enter key:");
scanf("%s", key);
printf("\nplease enter value:");
scanf("%s", value);
rv = SetCfgItem(CFG_FILENAME, key, value, strlen(value));
if (rv != 0)
{
printf("SetCfgItem() err: %d \n", rv);
goto End;
}
/*
rv = GetCfgItem(CFG_FILENAME, DB_sid, value2, &value2Len);
if (rv != 0)
{
printf("SetCfgItem() err: %d \n", rv);
goto End;
}
//比较长度
if (valuelen != value2Len)
{
printf("(valuelen != value2Len) err\n");
goto End;
}
//比较内容
if (memcmp(value, value2, value2Len) != 0)
{
printf("(memcmp(value, value2, value2Len)) err\n");
goto End;
}
*/
printf("读写配置项绿灯测试通过\n");
End:
return rv;
}
int Test_GetCfgItem()
{
int rv = 0;
int choice = 0;
char key[1024] ;
char value[1024];
int valueLen = 1024;
memset(key, 0, sizeof(key));
memset(value, 0, sizeof(value));
printf("\nplease enter key:");
scanf("%s", key);
//printf("\nplease enter value:");
//scanf("%s", value);
rv = GetCfgItem(CFG_FILENAME, key, value, &valueLen);
if (rv != 0)
{
printf("SetCfgItem() err: %d \n", rv);
goto End;
}
printf("\n%s = %s", key, value);
printf("\n读写配置项绿灯测试通过\n");
End:
return rv;
}
/*
int Test_GetCfgItem()
{
int rv = 0;
int choice = 0;
char *value = "orcl";
int valuelen = strlen(value);
char value2[100];
int value2Len = 100;
memset(value2, 0, sizeof(value2));
rv = SetCfgItem(CFG_FILENAME, DB_sid, value, valuelen);
if (rv != 0)
{
printf("SetCfgItem() err: %d \n", rv);
goto End;
}
rv = GetCfgItem(CFG_FILENAME, DB_sid, value2, &value2Len);
if (rv != 0)
{
printf("SetCfgItem() err: %d \n", rv);
goto End;
}
//比较长度
if (valuelen != value2Len)
{
printf("(valuelen != value2Len) err\n");
goto End;
}
//比较内容
if (memcmp(value, value2, value2Len) != 0)
{
printf("(memcmp(value, value2, value2Len)) err\n");
goto End;
}
printf("读写配置项绿灯测试通过\n");
End:
return rv;
}
*/
int main()
{
int rv = 0;
int choice = 0;
for(;;)
{
main_menu();
scanf("%d", &choice);
switch (choice)
{
case 1:
Test_SetCfgItem(); break;
case 2:
Test_GetCfgItem(); break;
case 0:
exit(0);
default:
exit(0);
}
}
End:
return rv;
getchar();
}