본문 바로가기

프로그래밍 언어/C, C++

fstream 처음 위치로 옮겨서 덮어쓰기

문제 상황

- 본인은 구조체를 파일에 쓰려고 하였다. 파일 스트림 std::fstream fIn({FILE_PATH}, std::ios::in | std::ios::out) 으로 파일을 열었고, 예를 들어 구조체 5개를 썼다. 하지만, 5개가 한번에 쓰여지는 상황은 아니고 (3개 + 2개) 혹은 (1개 + 4개)로 나뉘어서 씌여지는 상황이다.

- 이때 구조체는 다음과 같은 순서로 쓰여지는 문제가 발생하였다. 구조체 3개를 쓰고, 파일이 닫힌뒤 다시 열어서 쓰면 구조체 4번째, 5번째가 파일 처음에 위치하게 되었다. 즉, 기존에 쓰였던 파일이 뒤로 밀렸다.

struct{4}   // 최근에 쓴 구조체

struct{5}

struct{1}   // 이하 기존에 쓴 구조체

struct{2}

struct{3}

- 본인은 상식적으로 구조체를 순서대로 이어서 쓰고 싶었다. Append 모드를 사용하면 되지만, 최대 100개의 구조체만 쓸수 있고, 100개를 넘어가면 0번째로 넘어와 구조체를 덮어쓰어야 하기 때문에 Append 모드로도 열지 못하는 상황이었다.

 

※ 참고로 ios::out 모드로만 파일을 열면 파일 내용이 다 지워진다. (ios::in | ios::out) 모드로 열어야 파일 내용이 지워지지 않고 열린다.

 

(ios::out | ios::app) 모드로 열고, 파일 포인터를 파일 앞으로 옮기면 되지 라고 생각할지 모르나, ios::app 모드로 열면 파일 끝 부분이 오프셋(Offset) 즉, 기준점이 되어 파일 포인터가 파일 맨 처음으로 가지 않는다([2]정확히는 파일 쓰기를 하면 자동으로 파일 포인터를 맨 끝으로 옮긴다고 한다. 끝 말고는 다른 곳에 쓸 방법이 없다.)

 

해결 방법

본인은 std::fstream fIn({FILE_PATH}, std::ios::in | std::ios::out) 로 파일을 열어서, fin.seekg({구조체 크기} * 쓰여진 구조체 갯수) 만큼 이동하여 문제를 해결하였다. 

 

참고로, 본인이 보기에 C언어는 쓰면서, 읽을 수 있는 기능이 없어 보였다. (즉, c++ 처럼 읽으면서 쓰는게 가능한 fstream으로 파일 열기 기능) 따라서, 왠만하면 C++ 함수를 이용하도록 한다.

 

 

▶이하 도움을 받은 스택 오버플로우 질문 글들

[1] https://stackoverflow.com/questions/50359669/how-to-go-to-the-beginning-of-the-file-in-fstream

 

How to go to the beginning of the file in fstream?

I'm practicing file handling. I made a text file and wrote some characters in it, now I want the cursor to go to the beginning of the file and put a character there using seekp. Here is the code

stackoverflow.com

[2] https://stackoverflow.com/questions/10359702/c-filehandling-difference-between-iosapp-and-iosate?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa 

 

C++ Filehandling: Difference between ios::app and ios::ate?

What's the difference between ios::ate and ios:app when writing to a file. In my view, ios::app gives you the ability to move around in the file, whereas with ios::ate it can only read/write at the...

stackoverflow.com

[3] https://stackoverflow.com/questions/7300306/c-overwriting-data-in-a-file-at-a-particular-position

 

C++ overwriting data in a file at a particular position

i m having problem in overwriting some data in a file in c++. the code i m using is int main(){ fstream fout; fout.open("hello.txt",fstream::binary | fstream::out | fstream::app); pos=f...

stackoverflow.com

[4] https://codedragon.tistory.com/2252

 

fopen() & fclose() - 파일의 접근 모드 (r, w, a, r+, w+, a+), 파일 입출력 모드, 대표적인 표준 입출력 함

fopen()함수와 fclose()함수 헤더파일 stdio.h fopen()함수 파일 스트림을 생성하고 파일을 오픈 fclose()함수 파일 스트림을 닫고, 파일도 닫기 함수 원형 함수의 원형 설명 #include FILE* fopen (const char..

codedragon.tistory.com

 

반응형

'프로그래밍 언어 > C, C++' 카테고리의 다른 글

포인터 vs 참조자  (0) 2022.11.15
std::nothrow  (0) 2022.07.29
C++ 파일 입출력 정리  (1) 2022.02.14
Unit testing 이란  (0) 2022.02.13
void 포인터 용법 정리  (0) 2021.08.26