文件操作

// ProcessOutput.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"

static int GetFileSize(FILE *stream)
{
    int curPostion;
    int length;
    curPostion = ftell(stream);
    fseek(stream, 0L, SEEK_END);
    length = ftell(stream);
    fseek(stream, curPostion, SEEK_SET);
    return length;
}

int _tmain(int argc, _TCHAR* argv[])
{ 
    FILE    *fpIn,*fpOut;
    char    *pBuf;
    char *pBufHandle,*tmp,*tmp1;
    int     file_size;
    int     length;
    //if (argc != 2)
    //{
    //    printf("Error format,Usage: display filename1\n");
    //    return 0; //键入了错误的命令行,结束程序的执行
    //}
    //if ((fpIn = fopen(argv[1], "r")) == NULL)
    //"C:\\Users\\liu\\Desktop\\MCS1\\Turbo_decoding_Ue1_Sym2.dat"
    if ((fpIn = fopen("C:\\Users\\samni\\Desktop\\ProcessOutput\\data.dat", "r")) == NULL)
    {
        printf("file open err!\n");
        exit(1);
    }
    else
    {
        file_size = GetFileSize(fpIn);
    }
    if ((fpOut = fopen("C:\\Users\\samni\\Desktop\\ProcessOutput\\data1.dat", "w")) == NULL)
    {
        printf("file open err!\n");
        exit(1);
    }
    pBuf = (char *)malloc(file_size);
    
    length = fread(pBuf, sizeof(char), file_size, fpIn);
    pBufHandle = (char *)malloc(length * 2);
    pBuf[length] = '\0';
    tmp = pBufHandle;
    tmp1=pBuf;
    pBufHandle[0] = '0';
    pBufHandle[1] = 'x';
    pBufHandle += 2;
    while (*pBuf != '\0')
    {    
        if (*pBuf == '\n')
        {
            *(pBufHandle) = ',';
            *(++pBufHandle) = '\n';
            *(++pBufHandle) = '0';
            *(++pBufHandle) = 'x';
            pBuf++;
            pBufHandle++;
            continue;
        }
        *pBufHandle = *pBuf;
        pBuf++;
        pBufHandle++;
    }
    pBufHandle -= 4;
    *(pBufHandle) = '\n';
    *(++pBufHandle) = '\0';
    pBufHandle = tmp;
    pBuf=tmp1;

    fwrite(pBufHandle, 1, length * 2, fpOut);
    printf("File Size : %d\n", file_size);
    printf("Read Size : %d\n", length);

    printf("%s\n", pBuf);
    printf("%s\n", pBufHandle);
    //free(pBuf);
    //free(pBufHandle);
    fclose(fpIn); fclose(fpOut);
    system("pause");
    return 0;
}

 

posted @ 2016-09-22 20:18  alexliu2360  阅读(121)  评论(0编辑  收藏  举报