读书人

C语言读写资料

发布时间: 2012-10-28 09:54:44 作者: rapoo

C语言读写文件

#include <stdio.h>#include <stdlib.h>/** *读文件 */int rFile(){        FILE *fp;    int flen;    char *p;    /* 以只读方式打开文件 */    if((fp = fopen ("e:\\1.txt","r"))==NULL)    {        printf("\nfile open error\n");        exit(0);    }    fseek(fp,0L,SEEK_END); /* 定位到文件末尾 */    flen=ftell(fp); /* 得到文件大小 */    p=(char *)malloc(flen+1); /* 根据文件大小动态分配内存空间 */    if(p==NULL){        fclose(fp);        return 0;    }    fseek(fp,0L,SEEK_SET); /* 定位到文件开头 */    fread(p,flen,1,fp); /* 一次性读取全部文件内容 */    p[flen]=0; /* 字符串结束标志 */    printf("%s",p);    fclose(fp);    free(p);    getch();    return 0;}/** *写文件 */int wFile(){    FILE *stream;    stream = fopen("e:\\1.txt", "w+");    fprintf(stream, "hello world!");    printf("The file pointer is at byte \%ld\n", ftell(stream));    fclose(stream);    getch();    return 0;}int main(void){    /*rFile();*/    wFile();    return 0;}


#include <stdio.h>#include <stdlib.h>/** * function:二进制文件的复制。 * parameter:from 源文件路径 *          :to   目标文件路径 * author:leson * date:2011-12-5 * */int copyFile(const char* from,const char* to){    FILE *in,*out;    int flen;    char *p;    /**     *读文件     */    if((in = fopen (from,"rb"))==NULL){        printf("\nfile open error:1\n");        return 1;    }    fseek(in,0L,SEEK_END); /* 文件指针定位到文件末尾 */    flen=ftell(in); /* 得到文件大小 */    p=(char *)malloc(flen+1); /* 根据文件大小动态分配内存空间--经典*/    if(p==NULL){        fclose(in);        return 2;    }    fseek(in,0L,SEEK_SET); /* 定位到文件开头 */    fread(p,flen,1,in); /* 一次性读取全部文件内容 */    p[flen]=0; /* 字符串结束标志 */    /*printf("%s",p);*/    /**     * 写文件     */    if((out=fopen(to,"wb"))==NULL){        printf("\nFile open error:3");        return 3;    }    fwrite(p,flen,1,out);/*往文件里写*/    fclose(out);    fclose(in);    free(p);  /*动态分配的内存一定要free*/    return 0;}int main(void){    int r=99;    if((r=copyFile("d:\\down.txt","d:\\up.txt"))!=0){        printf("%d",r);    }    getch();    return 0;}

读书人网 >C语言

热点推荐