c语言文件读写示例(c语言文件操作)

时间:2021-05-20

方法:

复制代码 代码如下:
long filesize(char* filename);
char* file_get_contents(char* filename);
void file_put_contents(char* filename, char* data);

示例:

复制代码 代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
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, "https://");
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, 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);
}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章