long filesize(char* filename);
char* file_get_contents(char* filename);
void file_put_contents(char* filename,char* data);
示例:
#include
#include
#include
long filesize(char* filename);
char* file_get_contents(char* filename);
void file_put_contents(char* filename,char* data);
int main() {
printf("%s\n","----------------Begin---------------");
char* filename = "/tmp/tmp.txt";
file_put_contents(filename,"");
char* data = file_get_contents(filename);
printf("Fd:: %s\n",data);
printf("%s\n","----------------End-----------------");
return 0;
}
long filesize(char* filename) {
long length;
FILE* stream = fopen(filename,"rb");
if(!stream) return 0L;
fseek(stream,0L,SEEK_END);
length = ftell(stream);
fclose(stream);
return length;
}
char* file_get_contents(char* filename) {
FILE* fp = fopen(filename,"rb");
if(!fp) {
printf("%s\n","The file can not be opened.");
exit(0);
}
long length = filesize(filename);
char* buffer = (char*) malloc(length);
char buf[1024];
memset(buffer,0x00,sizeof(buffer));
fseek(fp,SEEK_SET);
while(fgets(buf,1024,fp) != NULL)
strcat (buffer,buf);
fclose(fp);
return buffer;
}
void file_put_contents(char* filename,char* data) {
FILE* fp = fopen(filename,"w+");
if(!fp) {
printf("The file can not be opened.\n");
exit(1);
}
fputs(data,fp);
fclose(fp);
}
总结
如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
小编个人微信号 jb51ccc
喜欢与人分享编程技术与工作经验,欢迎加入编程之家官方交流群!
如果觉得《读写c语言编程 c语言文件读写示例(c语言文件操作)》对你有帮助,请点赞、收藏,并留下你的观点哦!