C++에서 파일 처리를 통해 사용자는 외부 파일에서 데이터를 읽고 쓰고 업데이트할 수 있습니다. 이번 글에서는 C++로 파일에서 일부 데이터를 읽는 방법을 알아봅니다.
C++의 파일에서 읽기
C++에서 파일의 내용을 읽으려면 다음을 사용할 수 있습니다. std::ifstream> (입력 파일 스트림) 파일에 대한 입력 스트림을 생성합니다. 그런 다음 std::getline() 함수를 사용하여 이 파일에서 데이터를 읽고 이를 일부 로컬 문자열 객체에 저장할 수 있습니다.
접근하다
- 먼저 std::를 사용하여 파일을 엽니다.
ifstream inputFile('filePath').>Then, c>파일이 성공적으로 열렸는지 또는 사용하지 않는지 확인하세요.is_open()>그 반환false if>파일을 열 수 없으며 그렇지 않으면 true입니다.- 파일을 한 줄씩 읽기
using>std:: getline()>function and print the content.>Finally, close the file using>std::fstream::close()>.>
파일에서 읽는 C++ 프로그램
아래 예제에서는 C++에서 input.txt라는 파일의 내용을 열고 읽는 방법을 보여줍니다.
C++
// C++ program to read from a file> #include> #include> #include> using> namespace> std;> > int> main()> {> >// Open the input file named 'input.txt'> >ifstream inputFile(>'input.txt'>);> > >// Check if the file is successfully opened> >if> (!inputFile.is_open()) {> >cerr <<>'Error opening the file!'> << endl;> >return> 1;> >}> > >string line;>// Declare a string variable to store each> >// line of the file> > >// Read each line of the file and print it to the> >// standard output stream> >cout <<>'File Content: '> << endl;> >while> (getline(inputFile, line)) {> >cout << line << endl;>// Print the current line> >}> > >// Close the file> >inputFile.close();> > >return> 0;> }> |
>
>
산출
File Content: Hey Geek! Welcome to GfG. Happy Coding.>
시간 복잡도: O(n), 여기서 n은 읽을 문자 수입니다.
공간 복잡도: O(n)