일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- compare
- preprocessing
- digitalRead
- UNO
- flutter
- Pointer
- java
- 3D
- file access
- Unity
- sensor
- aduino
- wpf
- Read
- public
- inheritance
- Encapusulation
- stream
- mfc
- c++
- memory
- SERIAL
- length
- Barcode
- Contour
- APP
- parameter
- atmega328
- Android
- Class
- Today
- Total
폴크(FOLC)
네트워크 간의 데이터 연동(파일 공유) 관련 본문
두 대의 PC가 네트워크 드라이브를 통해 공유된 폴더에서 파일을 생성하고, 메시지를 주고받을때 아래과 같이 예외(Exception)가 발생할 수 있다.
원인
파일이 아직 완전히 생성되지 않았을 때 접근
파일 작성이 끝나기 전에 다른 PC에서 접근하면 IOException이나 FileNotFoundException이 발생할 수 있습니다.
버퍼링 및 파일 캐싱 문제
파일 시스템에서 파일 생성 직후에 바로 디스크에 반영되지 않아 접근 시 에러가 발생할 수 있습니다.
파일 잠금 (File Locking)
한쪽 PC에서 파일을 아직 닫지 않은 상태일 경우, 다른 PC가 파일을 읽으려 할 때 "사용 중" 예외가 날 수 있습니다.
방안
텍스트 파일 생성 → 완료 메시지 전송 → 수신 측에서 파일 안정성 체크 후 → 파일 읽기
원본 파일 다음으로 .chk 별도 확인 파일을 생성해서 안정성 체크
.chk 파일이 원본 파일 다음으로 가장 마지막에 생성되므로, 수신 측이 .chk 파일의 존재를 확인하면 원본 파일을 정상적으로 완성되었고 읽기 가능함을 신뢰할 수 있다.
< 예제 코드 >
송신 측 - raw.data 와 raw.data.chk 파일 생성 순서가 매우 중요함!
const std::string filepath = "raw.data";
std::ofstream file(filepath);
file << contents;
file.close(); // 중요: 반드시 flush & close
// 선택적으로 .ready 파일 생성
std::ofstream ready(filepath + ".chk");
ready << "done";
ready.close();
-> SendMessage ( 수신측으로 파일 생성을 완료하였음을 알려준다.)
수신 측 - .chk 파일이 생성되었는지 확인하고 성공하면 원본 파일을 읽어야 함.
const std::string filepath = "raw.data";
int retry = 0;
while (!isFileReady(filepath + ".chk"))
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
if (++retry > 50)
{
throw std::runtime_error("파일이 준비되지 않았습니다.");
return;
}
}
std::ifstream file(filepath);
if (!file.is_open())
{
throw std::runtime_error("파일 열기 실패");
return;
}
std::string line, all;
while (std::getline(file, line))
{
all += line + "\n";
}