c语言文件操作

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

int main()
{
    int len;
    char *ch=NULL;
    FILE *pfile=fopen("a.txt","r+");    //不用新建a.txt,下一个语句自动新建
    fwrite("hello,world",1,strlen("hello,world"),pfile);        //直接往空文件中写
    fflush(pfile);
    //fseek(pfile,0,SEEK_SET);//fseek用于移动文件指针。从文件开头开始重写
    //fwrite("发",1,strlen("发"),pfile);
    len=ftell(pfile);            //用于获取文件字节数
    
    ch=(char *)malloc(sizeof(char *)*(len+1));    //动态分配数组大小,故意大于len,用于表示结尾结束符
    memset(ch,0,(len+1));        //清空数组内容
    
    rewind(pfile);        //将指针复位到开始,便于从头读取
    fread(ch,1,len,pfile);            //将文件内容读取到数组ch中
    printf("%s\n",ch);            //ch中的最后一个字节为零,起到打印结尾标识符的作用
    
    
    return 0;
}

posted on 2015-03-07 22:26  weekman  阅读(103)  评论(0编辑  收藏  举报