티스토리 뷰


파일에서 문자 하나씩 읽기

C
FILE* fp;
fp = fopen("HelloWorld.txt", "r");

char character;
do
{
	character = getc(fp);
	printf("%c", character);
} while (character != EOF);

fclose(fp);

C++
ifstream fin;
fin.open("HelloWorld.txt");

char character;
while (true)
{
    fin.get(character);
    if (fin.fail())
    {
    	break;
    }
    cout << character;
}

fin.close();

 

get(), getline(), >>

  • 어떤 스트림(예: cin, istreingstream)을 넣어도 동일하게 동작
fin.get(character);

fin.getline(firstName, 20);	// 파일에서 문자 20개를 읽음
getline(fin, line);		// 파일에서 한 줄을 읽음

fin >> word;			// 파일에서 한 단어를 읽음

파일에서 한 줄씩 읽기

ifstream fin;
fin.open("Hello World.txt");

string line;
while (!fin.eof())
{
    getline(fin, line);
    cout << line << endl;
}

fin.close();

  해당 예문은 문제점이 하나있다. 아직은 추가하지 않았지만 만약에 빈파일을 읽으면 어떻게 될까? 파일은 비어있지만 결과는 한 줄이 출력된다. 그런 문제점을 생각하며 코딩해야한다.


파일에서 한 단어씩 읽기

ifstream fin;
fin.open("Hello World.txt");

string name;
float balance;
while (!fin.eof())
{
    fin >> name >> balance;
    cout << name << ": $" << balance << endl;
}

fin.close();

댓글