当前位置: 编程技术>c/c++/嵌入式
c语言文件读写示例(c语言文件操作)
来源: 互联网 发布时间:2014-10-23
本文导语: 方法: 代码如下: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* file...
方法:
代码如下:
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("%sn", "----------------Begin---------------");
char* filename = "/tmp/tmp.txt";
file_put_contents(filename, "http://www.");
char* data = file_get_contents(filename);
printf("Fd:: %sn", data);
printf("%sn", "----------------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("%sn", "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, 0L, 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);
}