std :: string을 파일에 쓰는 방법?
std::string
사용자로부터 받는 변수 를 파일에 쓰고 싶습니다 . 나는 write()
방법을 누군 고 파일에 씁니다. 그러나 대신 파일을 열면 대신 상자가 표시됩니다.
다중은 가변 길이 단일 단어입니다. 가 std::string
이 적합한 아니면 문자 배열 또는 무언가를 사용해야합니다.
ofstream write;
std::string studentName, roll, studentPassword, filename;
public:
void studentRegister()
{
cout<<"Enter roll number"<<endl;
cin>>roll;
cout<<"Enter your name"<<endl;
cin>>studentName;
cout<<"Enter password"<<endl;
cin>>studentPassword;
filename = roll + ".txt";
write.open(filename.c_str(), ios::out | ios::binary);
write.put(ch);
write.seekp(3, ios::beg);
write.write((char *)&studentPassword, sizeof(std::string));
write.close();`
}
현재 string
-object 의 바이너리 데이터를 파일 에 쓰고 있습니다. 이진 데이터는 실제 데이터에 대한 포인터와 길이가 긴 정수로만 구성됩니다.
텍스트 파일에 쓰려는 경우이를 수행하는 가장 좋은 방법은 아마도 ofstream
"아웃 파일 스트림"인을 사용하는 것입니다. 정확히 똑같이 동작 std::cout
하지만 출력은 파일에 기록됩니다.
다음 예제는 stdin에서 하나의 읽은 읽은 다음이 쓰고 파일에 씁니다 output.txt
.
#include <fstream>
#include <string>
#include <iostream>
int main()
{
std::string input;
std::cin >> input;
std::ofstream out("output.txt");
out << input;
out.close();
return 0;
}
참고 out.close()
여기에 엄격 하게이 켜지지되지 않습니다 :의 deconstructor이 ofstream
바로 우리를 위해이 문제를 해결할 수는 out
범위를 벗어나.
자세한 내용은 C ++ 참조를 참조하십시오. http://cplusplus.com/reference/fstream/ofstream/ofstream/
이제 바이너리 형식으로 파일에 기록해야하는 경우라면 실제 데이터를 사용하여 수행해야합니다. 이 데이터를 얻는 가장 쉬운 방법은 string::c_str()
. 따라서 다음을 사용할 수 있습니다.
write.write( studentPassword.c_str(), sizeof(char)*studentPassword.size() );
std::ofstream
파일에 쓰기 위해 사용하는 가정하면 다음 스 니펫은 std::string
사람이 읽을 수있는 형식으로 파일에 씁니다 .
std::ofstream file("filename");
std::string my_string = "Hello text in file\n";
file << my_string;
ios::binary
ofstream의 모드에서 제거하고 studentPassword.c_str()
대신 사용 (char *)&studentPassword
하십시오.write.write()
이 문제는 나를 짜증나게했고 xxd는 스크립트를 작성하려고 할 때 __home_myname_build_prog_cmakelists_src_autogen과 같은 변수를 만들었 기 때문에 내 사용 사례에서 작동하지 않으므로이 정확한 문제를 해결하는 유틸리티를 만들었습니다.
https://github.com/Exaeta/brcc
소스 및 헤더 파일을 생성하고 각 변수의 이름을 명시 적으로 설정하여 std :: begin (arrayname) 및 std :: end (arrayname)을 통해 사용할 수 있습니다.
나는 그것을 내 cmake 프로젝트에 다음과 같이 통합했습니다.
add_custom_command(
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/binary_resources.hpp ${CMAKE_CURRENT_BINARY_DIR}/binary_resources.cpp
COMMAND brcc ${CMAKE_CURRENT_BINARY_DIR}/binary_resources RGAME_BINARY_RESOURCES_HH txt_vertex_shader ${CMAKE_CURRENT_BINARY_DIR}/src/vertex_shader1.glsl
DEPENDS src/vertex_shader1.glsl)
작은 조정으로 C에서도 작동하도록 만들 수 있다고 생각합니다.
참고 URL : https://stackoverflow.com/questions/15388041/how-to-write-stdstring-to-file
'ProgramingTip' 카테고리의 다른 글
“require (x)”와 import x의 차이점 (0) | 2020.11.08 |
---|---|
L1 캐시 미스 비용은 얼마입니까? (0) | 2020.11.08 |
const 키와 non const 키의 차이점은 무엇입니까? (0) | 2020.11.08 |
Bash의 텍스트 파일에서 배열 만들기 (0) | 2020.11.08 |
콘솔에 인쇄 된 것을 잘리지 마십시오 (RStudio에서). (0) | 2020.11.08 |