c语言读取文件,写入文件

导入头文件

#include <stdlib.h>
#include <stdio.h>
读取文件
/**
read file
*/

char* readFile(char *filePath){
     FILE *fp;
    fp = fopen(filePath , "r");
    fseek( fp , 0 , SEEK_END );
    int file_size;
    file_size = ftell( fp );
    //printf( "%d" , file_size );
    char *tmp;
    fseek( fp , 0 , SEEK_SET);
    tmp =  (char *)malloc( file_size * sizeof( char ) );
    fread( tmp , file_size , sizeof(char) , fp);
    //printf("%s" , tmp );
    filePath = NULL;
  return tmp;
	
}

写入文件

/**

write file 
**/
void writeFile(char *tmp){
    //char *s="That's good news";   
    //int i=617;   
    FILE *fp;  
    
    fp=fopen("config/writePath.txt", "w"); /*建立一个文字文件只写*/   
   // fputs("Your score of TOEFL is",fp); /*向所建文件写入一串字符*/   
    //fputc(':', fp); /*向所建文件写冒号:*/   
   // fprintf(fp, "%d/n", i); /*向所建文件写一整型数*/   
    fprintf(fp, "%s", tmp); /*向所建文件写一字符串*/   
    fclose(fp);  
}


调用:

 int  main(){
   printf("start\n");
  
   char *tmp = readFile("config/config.txt");
   // printf("%s",tmp);//find file
    writeFile(tmp);
    tmp = NULL;
  printf("%s\n","end");
  return 0;
}





posted on 2017-03-21 11:44  愤怒的苹果ext  阅读(36)  评论(0编辑  收藏  举报

导航