6.c语言程序设计--文件操作

文件读取

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

int main()
{    
    FILE * pFile; //声明文件指针
    char * szReadTextBuffer; //存储我们读到的东西
    int nReadFileSize; //读取文件的尺寸
    int nReadRetSize; //返回真实长度
    pFile = fopen("F://1234.txt", "rb"); // r 读取 w 写出 b 二进制
    if (pFile == NULL) //判断是否读取成功
    {
        printf("Open file failed!");
        exit(0);//退出进程
    }
    fseek(pFile, 0, SEEK_END); //把文件指针移动到末尾
    nReadFileSize = ftell(pFile);//通过文件指针获取文件大小
    rewind(pFile);//把文件指针复位到最前面,方便后面的读取
    szReadTextBuffer = (char *)malloc((nReadFileSize * sizeof(char)) + 1); //申请内存

    if (szReadTextBuffer == NULL) //判读内存申请是否成功
    {
        printf("malloc memory failed!");
        exit(0);
    }
    memset(szReadTextBuffer, 0, nReadFileSize + 1); //把申请到的内存刷成0
    nReadRetSize = fread(szReadTextBuffer, 1, nReadFileSize, pFile);//读取到的真实长度, fread:把文件写入内存,返回长度
    if (nReadFileSize != nReadRetSize) //判断读取到的真实长度和文件的长度比较
    {
        printf("Read file failed!");
        exit(0);
    }
    //这个时候文件已经读取到内存里面了
    puts(szReadTextBuffer);//把读取到文件打印出来验证下
    fclose(pFile);//释放掉文件指针
    return 0;
}

运行结果:

文件写入

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{    
    char * szWriteBuffer = "hello wrold!";
    FILE * pFile;
    pFile = fopen("F://4321.txt", "wb");
    if (pFile == NULL) //判断是否读取成功
    {
        printf("Open file failed!");
        exit(0);//退出进程
    }
    fwrite(szWriteBuffer, strlen(szWriteBuffer), 1, pFile);
    fclose(pFile);
    return 0;
}

运行结果

原文地址:https://www.cnblogs.com/trevain/p/14466492.html