额
话说C/C++的文件读写本来就是基于平台的API的吧
代码
#include <iostream>
#include <windows.h>
struct _File
{
LPCSTR filename;
HANDLE handle = nullptr;
};
typedef _File* File;
File open(LPCSTR filename,bool read_mode);
LPSTR read(File file);
void write(File file, LPCSTR text);
void close(File& file);
int main()
{
File fw = open("a.txt",false);
write(fw, "text");
close(fw);
File fr = open("a.txt",true);
LPSTR text = read(fr);
std::cout << text << std::endl;
GlobalFree(text);
close(fr);
return 0;
}
File open(LPCSTR filename,bool read_mode)
{
if (filename != nullptr)
{
File result = new _File;
result->filename = filename;
result->handle = CreateFile(filename,(read_mode ? GENERIC_READ : GENERIC_WRITE), 0, 0,(read_mode ? OPEN_EXISTING : CREATE_ALWAYS),FILE_ATTRIBUTE_NORMAL, 0);
if (result->handle == INVALID_HANDLE_VALUE) return nullptr;
return result;
}
std::cout << "filename is null" << std::endl;
return nullptr;
}
LPSTR read(File file)
{
if (file != INVALID_HANDLE_VALUE)
{
size_t file_size = GetFileSize(file->handle, nullptr);
if (file_size == INVALID_FILE_SIZE)
{
std::cout << "file size is INVALID_FILE_SIZE" << std::endl;
return nullptr;
}
LPSTR result = (LPSTR)GlobalAlloc(GPTR,file_size + 1);
if(ReadFile(file->handle,result,file_size,nullptr,nullptr) == 0)
{
std::cout << "Failed to read file:\"" << file->filename << "\"" << std::endl;
delete[] result;
return nullptr;
}
result[file_size] = '\0';
return result;
}
return nullptr;
}
void write(File file, LPCSTR text)
{
if (file != INVALID_HANDLE_VALUE && text != nullptr)
{
WriteFile(file->handle, text, strlen(text), nullptr, nullptr);
}
}
void close(File& file)
{
if (file != nullptr)
{
if (file->handle != INVALID_HANDLE_VALUE) CloseHandle(file->handle);
delete file;
file = nullptr;
}
}
运行结果
控制台
text
--------------------------------
Process exited after 0.6997 seconds with return value 0
请按任意键继续. . .
a.txt
text
|