二级指针配合文件读写

读取配置文件信息,并且将信息存放到数组中

注意:释放堆区,关闭文件

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

//获取有效行数
int getFileLines(FILE *pfile){
    if(pfile==NULL){
        return -1;
    }
    int len=0;
    char buf[1024]={0};
    while(fgets(buf,1024,pfile)!=NULL){
        len++;
//        printf("%s",buf);
    }
    //将文件光标置为首,
    fseek(pfile,0,SEEK_SET);//从文件的最开始偏移0个位置
    return len;
}
//读取数据放入到pArray中
void readFileData(FILE * pFile,int len,char **pArray){
    if(pFile==NULL){
        return ;
    }
    if(len<=0){
        return;
    }
    if(pArray==NULL){
        return ;
    }
    char buf[1024]={0};
    int index=0;
    while (fgets(buf,1024,pFile)!=NULL){
        int currentLen=strlen(buf)+1;
        char *currentStrP=malloc(sizeof(char )*currentLen);
        strcpy(currentStrP,buf);
        pArray[index++]=currentStrP;
        memset(buf,0,1024);
    }

}
//打印数组
void showFileData(char ** pArray,int len){
    for (int i = 0; i < len; ++i) {
        printf("%s",pArray[i]);
    }
}

void test01(){
    FILE *pFile=fopen("../C_Senior/erjizhizhenpeihewenjianduxie.txt","r");
    if (pFile==NULL){
        printf("error while open the file you pointed");
        return;
    }

    //统计有效行数,注意这里在运行完函数getFileLines之后,文件指针不再是文件头部了,要改回文件指针的偏移,fseek(pFile,0,SEEK_SET);
    int len=getFileLines(pFile);//pFile发生了指针的偏移,文件光标在最后一行内容的下一行了
    char ** pArray=malloc(sizeof(char *)*len);
    //读取文件中的数据并且放入到pArray
    readFileData(pFile,len,pArray);
    //读取数据
    showFileData(pArray,len);//
    free(pArray);
    pArray=NULL;
    fclose(pFile);

}

int main(){
    test01();
    return 0;
}

a对齐 到 b
(a+(b-1))& ~(b-1)

posted @ 2022-02-27 13:03  WEIWEI1095  阅读(46)  评论(0)    收藏  举报
*/
作品集 //