文件读写1

2021-07-19  本文已影响0人  李永开
//
//  main.c
//  cdemo
//
//  Created by liyongkai on 2021/6/6.
//

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


//获取文件行数
int getFileLines(FILE *file) {
    if (NULL == file) return -1;
    
    int lines = 0;
    char buffer[1024] = {0};
    while(fgets(buffer, 1024, file) != NULL) {
        lines ++;
    }
    return lines;
}

//读取数据
void readDataFromFile(FILE *file, int lines, char** contents) {
    if (NULL == file) return;
    if (lines <= 0) return;
    if (NULL == contents) return;
    
    char buffer[1024] = {0};
    int i = 0;
    while (fgets(buffer, 1024, file) != NULL) {
        unsigned long lineLen = strlen(buffer) + 1;
        char *lineP = malloc(lineLen * sizeof(char *));
        strcpy(lineP, buffer);
        contents[i++] = lineP;
//        printf("%s\n",buffer);
    }
}

//打印文本内容
void showContent(char **contents, int lines) {
    for (int i = 0; i < lines; i ++) {
        printf("%s", contents[i]);
    }
}

//释放
void freeFileSpace(char **contents, int lines) {
    for (int i = 0; i < lines; i ++) {
        if (contents[i] != NULL) {
            free(contents[i]);
        }
    }
    
    free(contents);
    contents = NULL;
}

int main(int argc, const char * argv[]) {
    FILE *file = fopen("/Users/LYK/Desktop/cdemo/cdemo/test.txt", "r");
    if (NULL == file) {
        printf("打开文件失败\n");
    }
    
    int lines = getFileLines(file);
    fseek(file, 0, SEEK_SET);//恢复文件指针到文件开始部分
    char **contents = malloc(lines * sizeof(char*));
    
    //读取文件
    readDataFromFile(file, lines, contents);
    
    //关闭文件
    fclose(file);
    file = NULL;
    
    //打印文件
    showContent(contents, lines);
    
    //释放文件数据
    freeFileSpace(contents, lines);
}


上一篇 下一篇

猜你喜欢

热点阅读