ProgramingTip

C ++로 파일 만들기

bestdevel 2020. 11. 30. 19:25
반응형

C ++로 파일 만들기


C ++를 사용하여 파일을 만들고 싶지만 어떻게할지 모르겠습니다. 예를 들어 .txt라는 텍스트 파일을 만들고 싶습니다 Hello.txt.

누구든지 나를 도울 수 있습니까?


이를 수행하는 한 가지 방법은 ofstream 클래스의 인스턴스를 만들고이를 사용하여 파일에 쓰는 것입니다. 다음은 몇 가지 예제 코드와 대부분의 C ++ 구현에서 사용할 수있는 표준 도구에 대한 추가 정보가있는 웹 사이트 링크입니다.

ofstream 참조

완전성을 위해 다음은 몇 가지 예제 코드입니다.

// using ofstream constructors.
#include <iostream>
#include <fstream>  

std::ofstream outfile ("test.txt");

outfile << "my text here!" << std::endl;

outfile.close();

std :: endl을 사용하여 줄을 끝내고 싶습니다. 대안은 '\ n'문자를 사용하는 것입니다. 이 두 가지가 나열. std :: endl은 버퍼를 비우고 출력을 즉시 기록하는 반면 '\ n'은 파일이 모든 출력을 버퍼에 나중에 쓸 수 있습니다.


파일 스트림으로이를 수행하십시오. A는 때 std::ofstream닫혀 파일이 만들어집니다. OP는 파일을 작성하지 않고 작성 요청하기 때문에 개인적으로 다음 코드를 좋아합니다.

#include <fstream>

int main()
{
    std::ofstream file { "Hello.txt" };
    // Hello.txt has been created here
}

임시 변수 file는 생성 파일이 생성됩니다.


#include <iostream>
#include <fstream>

int main() {
  std::ofstream o("Hello.txt");

  o << "Hello, World\n" << std::endl;

  return 0;
}

내 해결은 다음과 달라집니다.

#include <fstream>

int main()
{
    std::ofstream ("Hello.txt");
    return 0;
}

ofstream 이름 없이도 파일 (Hello.txt)이 생성 완료되고 Boiethios 씨의 답변과 처리됩니다.


#include <iostream>
#include <fstream>
#include <string>
using namespace std;

string filename = "/tmp/filename.txt";

int main() {
  std::ofstream o(filename.c_str());

  o << "Hello, World\n" << std::endl;

  return 0;
}

이것은 일반 범용 대신 파일 이름에 변수를 사용하기 위해 수행해야하는 작업입니다.


/*I am working with turbo c++ compiler so namespace std is not used by me.Also i am familiar with turbo.*/

#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
#include<fstream.h> //required while dealing with files
void main ()
{
clrscr();
ofstream fout; //object created **fout**
fout.open("your desired file name + extension");
fout<<"contents to be written inside the file"<<endl;
fout.close();
getch();
} 

프로그램을 실행하면 컴파일러 폴더 자체의 bin 폴더에 파일이 생성됩니다.

참고 URL : https://stackoverflow.com/questions/478075/creating-files-in-c

반응형