로그인

검색

C/C++
2013.07.28 02:50

ofstream ifstream

MoA
조회 수 3529 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 게시글 수정 내역 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 게시글 수정 내역 댓글로 가기 인쇄

ofstream

 

n  파일로부터 읽어들이거나 쓰기 위해 사용되는 특수한 객체를 ofstream객체라 한다.

n  ofstream 객체는 iostream 객체로부터 파생되었다.

n  파일에 쓰려면 ofstream 객체를 만들고 디스크의 특정 파일과 연결지어야 한다.

n  ofstream 객체를 사용하려면 먼저 프로그래머는 #include <fstream.h>를 포함해야 한다.

 

 

조건을 나타내는 상태

 

n  iostream 객체는 입력과 출력 상태를 알리는 플래그를 가지고 있다.

n  불린 함수 eof(), bad(), fail(), good()를 사용하여 이 플래그들을 검사할 수 있다.

-       eof() : iostream 객체가 EOF를 만나면 참값을 반환한다.

-       bad() :  유효하지 않은 연산자를 시도하려면 참값을 반환

-       fail() : bad() 함수가 실패하면

-       good() : 위의 세 개의 함수가 거짓을 참을 반환한다.

 

입출력을 위한 파일 열기

n  만약 ttext.txt 파일을 ofstream 객체로 열기 위해 ofstream 객체의 인스턴스를 선언하고 매개 변수로 파일 이름을 전달한다.

-       ofstream fout(“text.txt”);

n  입력용으로 열기 위한 방법

-       ifstream fin(“text.txt”);

n  close()

-       읽기용이나 쓰기용읽고 동시에 쓰기용으로 열어놓은 파일은 입출력을 마친 뒤 사용을 한다.

 

 

순차 접근 파일 생성

 

#include<iostream>

#include<fstream>

using std::ofstream; //파일에 쓰기용

 

File Access Type

ios::app 파일 끝에 모든 출력을 추가

ios::ate 출력을 위해 파일을 열고 파일의 끝으로 이동

ios::in 입력용 파일 열기

ios::out 출력용 파일 열기

ios::trunc 파일이 존재한다면, 파일 내용을 모두 삭제(ios::out을 위한 디폴트 동작)

ios::binary 텍스트가 아닌 이진으로 입출력하기 위한 파일열기


int main()
{

   int accoount;
   char name[30];
   double balance;
 
  ofstream outFile("test.dat",ios::out); //파일을 연다, 없으면 생성
  while(cin>>account>>name>>balance)
      outFile<<account<<' '<<name<<' '<<balance<<endl;  //이런형식으로 저장됨
  return 0;

}


 순차 접근 파일에서데이터 읽기

 
using std::ifstream; //파일 읽기용 
 

istream : seekg(seek get) //읽기용 포인터 탐색

ostream : seekp(seek put) //쓰기용 포인터 탐색

 

예)

  fileObject.seekg(n); //fileObject의 n바이트로 이동(디폴트ios::beg)

  fileObject.seekg(n, ios::cur); //fileObject의 현재 위치에서 n바이트 앞으로 이동

  fileObject.seekg(n, ios::end); //fileObject의 끝에서 뒤로 n바이트로 이동

  fileObject.seek(0, ios::end); //fileObject의 끝으로 이동

 

int main()
{

   int accoount;
   char name[30];
   double balance;
 
  ifstream inFile("test.dat",ios::in);   //읽을 파일을 연다.
  while(inFile>>account>>name>>balance)
      cout << account << ' ' << name << ' ' << balance << endl;  //이런형식으로 저장됨
  return 0;

}


임의 접근 파일에 임의로 데이터 쓰기

 

#include<fstream>
 
using std::ofstream;
using std::ifstream;
 
typedef struct {
   char name[16];
   int    id[20];
   int age;
}  Student;
 
Student memb;
 
int main()
{
 
// case 1
   ifstream inFile("testIn.dat",ios::in);
  inFile.read(reinterpret_cast<char*>(&memb), sizeof(Student));
 
  ofstream outFile("testOut.data",ios::binary);
  outFile.seekp(0, ios::end);
  outFile.write(reinterpret_cast<const char*>(&memb),sizeof(Student));
 
// Case 2
  while(inFile&& !inFile.eof())  {    //파일의 끝까지 모든 레코드를 읽음
      inFile.read(reinterpret_cast<char*>(&memb),sizeof(Student));       //다음 레코드를 읽음
      outFile.write(reinterpret_cast<const char*>(&memb),sizeof(Student));
  }
 
// Case 3
  fstream outFile("testmemb.dat",ios::in | ios::out); //읽고 쓰기위한 파일 열기
 
  return 0;


파일 열고 쓰기 예

 

/*
*  읽기와쓰기용으로파일을열기
*/
 
#include <fstream>
#include <iostream>
using namespace std;
 
char gbuffer[1024];    
char fileName[80];
 
int main()
{
        cout << "file name: ";
        cin >> fileName;
 
        /// 쓰기용
        ofstream fout(fileName);
        fout << "this line written directory to the file.....n";
        cout << "Enter text for the file:";
        /// 파일뒤에개행문자를없앤다.
        cin.ignore(1,'n');
 
        /// 사용자입력을받는다.
        cin.getline(gbuffer, 255);
 
        /// 파일에쓴다.
        fout << gbuffer<< "n";
 
        /// 파일객체를닫고다시열기를기다린다.
        fout.close();
 
        /// 읽기를위해서스트림을다시연다
        ifstream fin(fileName);
        cout << "Here's the contents of the file: n";
        char ch;
        while (fin.get(ch))
        {
               cout << ch;
        }
 
        cout << "n";
        cout << "### End of file contents ###n";
        fin.close();
        return 0;
}



http://blog.naver.com/dolicom/10086114631

?

  1. Programming 게시판 관련

    Date2014.11.01 CategoryTool/etc ByMoA Views15454
    read more
  2. 알리바바, 딥시크·오픈AI 넘는 추론 모델 출시..."오픈 소스 최강 입증" (QwQ-32B)

    Date2025.03.10 CategoryLLM ByOBG Views1204
    Read More
  3. 존 카맥이 일리야 수츠키버를 4년전에 만났을때, 추천받은 책과 논문 목록

    Date2025.02.18 CategoryDeeplearning ByOBG Views1339
    Read More
  4. 2024년 가장 조회수 높은 소프트웨어 엔지니어링 발표들

    Date2025.02.18 CategorySite ByOBG Views1405
    Read More
  5. OS 개발에 관한 작은 책

    Date2025.03.24 CategoryTool/etc ByOBG Views1440
    Read More
  6. AI-hub 공공데이터를 활용하여 한국어-영어 번역 LLM 만들기

    Date2025.01.14 CategoryLLM ByOBG Views1568
    Read More
  7. llama3 implemented from scratch

    Date2024.05.24 CategoryLLM ByOBG Views1618
    Read More
  8. 얼렁뚱땅 LLM을 만들어보자

    Date2025.01.10 CategoryLLM ByOBG Views1648
    Read More
  9. PEFT: Parameter-Efficient Fine-Tuning of Billion-Scale Models on Low-Resource Hardware

    Date2024.04.15 CategoryLLM ByOBG Views1681
    Read More
  10. A Beginner's Guide to Prompt Engineering with GitHub Copilot

    Date2024.04.04 CategoryLLM ByOBG Views1784
    Read More
  11. GDB Dashboard

    Date2025.01.14 CategoryTool/etc ByOBG Views1807
    Read More
  12. GitHut Copilot - Agent 모드 공개

    Date2025.02.14 CategoryTool/etc ByOBG Views1869
    Read More
  13. OS in 1,000 Lines

    Date2025.01.14 CategoryTool/etc ByOBG Views1879
    Read More
  14. Caching in Node.js to optimize app performance

    Date2023.01.16 Category서버 ByOBG Views1939
    Read More
  15. Debugging Node.js Memory Leaks: How to Detect, Solve or Avoid Them in Applications

    Date2023.07.04 Category서버 ByOBG Views1943
    Read More
  16. 나이 들어가는 프로그래머 - [발표영상] 요약

    Date2025.02.14 CategoryTool/etc ByOBG Views2009
    Read More
  17. PyTorch 딥러닝 챗봇

    Date2023.07.04 CategoryDeeplearning ByOBG Views2141
    Read More
  18. Mixture of Experts - Part 2

    Date2024.04.14 CategoryLLM ByOBG Views2141
    Read More
  19. Creating A Fixed-Length Queue In JavaScript Using Arrays

    Date2022.09.14 CategoryWeb ByOBG Views2195
    Read More
  20. 멀티-플레이어 게임 서버와 레이턴시 보상 테크닉

    Date2024.01.16 Category서버 ByOBG Views2203
    Read More
  21. Design a Basic Search Engine (Google or Bing) | System Design Interview Prep

    Date2023.05.27 Category서버 ByOBG Views2207
    Read More
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 15 Next
/ 15