//头文件
#pragma once
#include <string>
/*
*@bref 读取文件内容
*@bref 输入 file,输出 content
*@bref return true读取成功,false读取失败
*/
bool getFileContents(const char *file, std::string &content);
/*
*@bref 写入数据到文件
*@bref 输入 text,输入 file
*@bref return true写入成功,false写入失败
*/
bool writeContentsToFile(const char *text, const char *file);
//源文件
#include "filerw.h"
#include <stdio.h>
#include <stdio.h>
bool getFileContents(const char *file, std::string &content)
{
FILE *fp = nullptr;
if (fopen_s(&fp, file, "rb") == 0)
{
char tmp[1024] = { 0 };
fseek(fp, 0, SEEK_END);
long len = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *data = (char *)malloc(len + 1);
memset(data, 0, len + 1);
rewind(fp);
while (fgets(tmp, 1024, fp) != NULL)
{
strcat_s(data, len + 1, tmp);
}
content = data;
free(data);
fclose(fp);
return true;
}
return false;
}
bool writeContentsToFile(const char *text, const char *file)
{
FILE *fp = nullptr;
if (fopen_s(&fp, file, "w+t") == 0)
{
fwrite(text, sizeof(char), strlen(text), fp);
fflush(fp);
fclose(fp);
fp = nullptr;
return true;
}
return false;
}
//测试例子
#include<stdio.h>
#include "filerw.h"
int main(int argc, char *argv[])
{
std::string strData = "";
char *fileName = "D:/project/FileRWPro/Debug/test.txt";
if (getFileContents(fileName, strData))
{
printf_s(" read file contents success ...\n");
}
char *fileName2 = "D:/project/FileRWPro/Debug/test_bk.txt";
if (writeContentsToFile(strData.c_str(), fileName2))
{
printf_s(" write text to file success ...\n");
}
return 0;
}