본문 바로가기
프로그래밍/C & C++

ifstream, ofstream을 이용한 file 입출력

by 체리 2022. 1. 25.
반응형

ifstream, ofstream을 이용한 file 입출력 방법

ifstream의 경우 ios::trunc를 주게되면 open이 되지 않는다. (good()이 false)

 

결과 부터 보기

 not same
 same

 

그 다음에 code 보기

- 필요시 fstream:trunc는 제거

#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdio>

using namespace std;

class FileIo
{
public:
    FileIo(void) = delete;
    explicit FileIo(const std::string& fileName)
    : fileName(fileName)
    {
        file.open(fileName, std::ios::binary | std::ios::in | std::ios::out | std::ios::ate | fstream::trunc);
    }
    virtual ~FileIo(void)
    {
        file.close();
    }
    virtual bool Write(void* const buf, const size_t byteOffset, const size_t byteSize)
    {
        file.seekp(byteOffset, file.beg);
        file.write(static_cast<char*>(buf), byteSize);
        if (!file.good())
        {
            return false;
        }
        return true;
    }
    virtual bool Read(void* buf, const size_t byteOffset, const size_t byteSize)
    {
        file.seekg(byteOffset);
        file.read((char*)buf, byteSize);
        if (!file.good())
        {
            return false;
        }
        return true;
    }

private:
    std::string fileName;
    std::fstream file;
};

int main()
{
    FileIo file("test.bin");

    char* writeBuf = new char[4096];
    char* readBuf = new char[4096];

    memset(writeBuf, 0x12345678, 4096);
    memset(readBuf, 0, 4096);

    if (!file.Write(writeBuf, 4096, 4096))
        cout << "write fail" << endl;

    if (!file.Read(readBuf, 0, 4096))
        cout << "read fail" << endl;

    if (std::equal(readBuf, readBuf + 4096, writeBuf))
        cout << "same" << endl;
    else
        cout << "not same" << endl;

    if (!file.Read(readBuf, 4096, 4096))
        cout << "read fail" << endl;

    if (std::equal(readBuf, readBuf + 4096, writeBuf))
        cout << "same" << endl;
    else
        cout << "not same" << endl;

    delete writeBuf;
    delete readBuf;

    return 0;
}
반응형

댓글