海阔天空

海阔凭鱼跃 天高任鸟飞

 

C语言文件的读写操作,每次读取1K,然后写入另外一个文件

C语言文件的读写操作,以二进制方式,每次读取1K,然后写入另外一个文件。输入的文件名和路径不能包含空格。

 

// File_RW.cpp : Defines the entry point for the console application.

//


#include "stdafx.h"


#define BUFSIZE 1024 

/////////////////////////////////////////////

#include <memory.h>

// memset(filePath, '\0', 512);函数的头文件

/////////////////////////////////////////////

#include <stdlib.h> 

// system("pause");函数的头文件


int main(int argc, char* argv[])

{

    printf("Hello World!\n\n");

    printf("///////////////////////////////////////////\n");

    char filePath[512];

    memset(filePath, '\0', 512);


    printf("Please input a file path!\n");

    // 输入的文件名和路径不能包含空格。

    scanf("%s", filePath);


    FILE*fp;// 读取文件

    FILE *ofp;// 写入文件


    fp = fopen(filePath, "rb");// 以二进制方式读取

    fseek(fp, 0, SEEK_SET);

    fseek(fp, 0, SEEK_END);

    long longBytes = ftell(fp);// 获取文件大小

    printf("The file size is: %d\n", longBytes);


    char RdBuffer[BUFSIZE];// 读取文件的缓冲数组

    fseek(fp, 0, SEEK_SET);

    ofp = fopen("outfile", "ab");   // 以二进制写方式打开文件 

    

    // 读取文件的循环 

    int ReadedLen = 0; // 读取大小计数

    int leftLen = longBytes; // 剩余大小计数


    while(1)

    {

        if((leftLen <= 0)||(ReadedLen >= longBytes)) //剩下长度为0或当前已发送长度为文件长则退出

            break;


        if(leftLen >= BUFSIZE)

        {

            memset(RdBuffer, '\0', BUFSIZE);

            fread(RdBuffer, BUFSIZE, 1, fp); 

            fwrite(RdBuffer, BUFSIZE, 1, ofp);

            ReadedLen += BUFSIZE;

        }

        else

        {

            memset(RdBuffer, '\0', BUFSIZE);

            fread(RdBuffer, leftLen, 1, fp);

            fwrite(RdBuffer, leftLen, 1, ofp);

            ReadedLen += leftLen;

        }

        leftLen=longBytes - ReadedLen;

    }


    fclose(fp);

    fclose(ofp);

    

    printf("\n");

    printf("///////////////////////////////////////////\n");


    system("pause");


    return 0;

}


 

posted on 2010-04-28 10:47  liuym  阅读(2813)  评论(0编辑  收藏  举报

导航