반응형
C ++에서 텍스트 파일에 텍스트를 추가하는 방법은 무엇입니까?
C ++에서 텍스트 파일에 텍스트를 추가하는 방법은 무엇입니까? 존재하지 않는 경우 새로 작성하고 존재하는 경우 추가하십시오.
#include <fstream>
int main() {
std::ofstream outfile;
outfile.open("test.txt", std::ios_base::app);
outfile << "Data";
return 0;
}
#include <fstream>
#include <iostream>
FILE * pFileTXT;
int counter
int main()
{
pFileTXT = fopen ("aTextFile.txt","a");// use "a" for append, "w" to overwrite, previous content will be deleted
for(counter=0;counter<9;counter++)
fprintf (pFileTXT, "%c", characterarray[counter] );// character array to file
fprintf(pFileTXT,"\n");// newline
for(counter=0;counter<9;counter++)
fprintf (pFileTXT, "%d", digitarray[counter] ); // numerical to file
fprintf(pFileTXT,"A Sentence"); // String to file
fprintf (pFileXML,"%.2x",character); // Printing hex value, 0x31 if character= 1
fclose (pFileTXT); // must close after opening
return 0;
}
이 코드를 사용합니다. 파일이 존재하지 않는 경우 파일을 작성하고 약간의 오류 검사를 추가합니다.
static void appendLineToFile(string filepath, string line)
{
std::ofstream file;
//can't enable exception now because of gcc bug that raises ios_base::failure with useless message
//file.exceptions(file.exceptions() | std::ios::failbit);
file.open(filepath, std::ios::out | std::ios::app);
if (file.fail())
throw std::ios_base::failure(std::strerror(errno));
//make sure write fails with exception if something is wrong
file.exceptions(file.exceptions() | std::ios::failbit | std::ifstream::badbit);
file << line << std::endl;
}
당신은 또한 이렇게 할 수 있습니다
#include <fstream>
int main(){
std::ofstream ost {outputfile, std::ios_base::app};
ost.open(outputfile);
ost << "something you want to add to your outputfile";
ost.close();
return 0;
}
"C ++ Programming In Easy Steps"라는 책에서 해답에 대한 코드를 얻었습니다. 아래는 가능합니다.
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int main()
{
ofstream writer("filename.file-extension" , ios::app);
if (!writer)
{
cout << "Error Opening File" << endl;
return -1;
}
string info = "insert text here";
writer.append(info);
writer << info << endl;
writer.close;
return 0;
}
이것이 도움이되기를 바랍니다.
를 사용 fstream
하여 std::ios::app
플래그로 열 수 있습니다 . 아래 코드를 살펴보면 머리가 깨끗해야합니다.
...
fstream f("filename.ext", f.out | f.app);
f << "any";
f << "text";
f << "written";
f << "wll";
f << "be append";
...
당신은 오픈 모드에 대한 자세한 정보를 찾을 수 있습니다 여기에 약하는 fstreams 여기 .
참고 URL : https://stackoverflow.com/questions/2393345/how-to-append-text-to-a-text-file-in-c
반응형
'programing tip' 카테고리의 다른 글
"OR"을 사용하여 여러 조건을 결합하여 데이터 프레임의 하위 세트를 만드는 방법은 무엇입니까? (0) | 2020.05.30 |
---|---|
Java의 콜백 함수 (0) | 2020.05.30 |
$ .ajax를 사용하여 쿼리 문자열 대신 JSON을 보내는 방법은 무엇입니까? (0) | 2020.05.30 |
if (포인터! = NULL) 대신 if (포인터)를 사용할 수 있습니까? (0) | 2020.05.30 |
"유형화되지 않은"은 또한 학문적 CS 세계에서 "동적 유형화 된"을 의미합니까? (0) | 2020.05.30 |