2012-11-28 2 views
2

항상 그렇듯이 포인터 문제가 있습니다. 이번에는 파일 (바이너리 모드로 열림)을 읽고 std :: string 객체에 그 일부를 저장하려고합니다. 보기 :C++ fread()를 std :: string으로 변환

FILE* myfile = fopen("myfile.bin", "rb"); 
if (myfile != NULL) { 
    short stringlength = 6; 
    string mystring; 
    fseek(myfile , 0, SEEK_SET); 
    fread((char*)mystring.c_str(), sizeof(char), (size_t)stringlength, myfile); 
    cout << mystring; 
    fclose(myfile); 
} 

이게 가능합니까? 나는 어떤 메시지도받지 않는다. 파일이 O.K입니다. char *로 시도하면 작동하지만 문자열에 직접 저장하려고합니다. 당신의 도움을 주셔서 감사합니다!

+4

친구 ... 당신은 c_str에서 얻을() ... 가변 주석 위 –

+0

하지 않고 모두 올바른을 아래에 대답,하지만 당신은 C++를 사용하는 경우 당신은 왜 파일 I에 대한 C 관용구를 사용하고있는/O –

+2

그리고 출력을 바로 가기 위해 C++ 스트리밍. –

답변

4

다음은 예이다.

FILE* myfile = fopen("myfile.bin", "rb"); 
if (myfile != NULL) { 
    short stringlength = 6; 
    string mystring(stringlength, '\0'); 
    fseek(myfile , 0, SEEK_SET); 
    fread(&mystring[0], sizeof(char), (size_t)stringlength, myfile); 
    cout << mystring; 
    fclose(myfile); 
} 

이 코드의 많은, 많은 문제가있다하지만 제대로 std::string를 사용하는 최소한의 조정이다.

1

프로그램에 문제가있는 사항을 보려면 c_str에 관해 다음을 확인하십시오. 몇 가지 문제는 c_str을 수정할 수 없지만 문자열 내용에 대한 포인터를 반환하지만 문자열을 초기화 한 적이 없다는 것을 포함합니다.

http://www.cplusplus.com/reference/string/string/c_str/

를 해결하기위한 것처럼 ... 당신은 숯불 *에 읽기 시도하고 그에서 문자열을 초기화 할 수있다.

3

string::c_str()은 수정할 수없는 const char*을 반환합니다.

한 가지 방법은 char * first를 사용하여 문자열을 구성하는 것입니다. 당신이 문자열을 원하는 경우

다음 다시
char buffer = malloc(stringlength * sizeof(char)); 
fread(buffer, sizeof(char), (size_t)stringlength, myfile); 
string mystring(buffer); 
free(buffer); 

그러나, 당신은 아마도 자신 Why am I using fopen and fread in the first place??

fstream 훨씬 더 나은 옵션이 될 것이다 요청해야합니다. 자세히 알아보기 here

+0

배열 길이는 상수 여야합니다. C++에는 가변 길이 배열이 없습니다. –

+0

나는 그것을 지적 주셔서 감사합니다 :) 내 대답을 고정 –

+0

고정 .. –

1

아니요. std::string::c_str() 메서드는 here에서 유효성을 검사 할 수 있으므로 수정 가능한 문자 시퀀스를 반환하지 않습니다. 더 나은 해결책은 버퍼 char 배열을 사용하는 것입니다. 버퍼 오버런을 방지하고 std::stringconst 및 기타 요구를 충족 &mystring[0]로서 바이트 배열 액세스 제 충분히 커야하는 캐릭터를 설정

FILE* myfile = fopen("myfile.bin", "rb"); 
    if (myfile != NULL) { 
     char buffer[7]; //Or you can use malloc()/new instead. 
     short stringlength = 6; 
     fseek(myfile , 0, SEEK_SET); 
     fread(buffer, sizeof(char), (size_t)stringlength, myfile); 
     string mystring(buffer); 
     cout << mystring; 
     fclose(myfile); 
     //use free() or delete if buffer is allocated dynamically 
} 
2

나는 이런 일을하는 가장 좋은 방법이라고 권장합니다. 또한 모든 바이트를 읽었는지 확인해야합니다.

FILE* sFile = fopen(this->file.c_str(), "r"); 

    // if unable to open file 
    if (sFile == nullptr) 
    { 
     return false; 
    } 

    // seek to end of file 
    fseek(sFile, 0, SEEK_END); 

    // get current file position which is end from seek 
    size_t size = ftell(sFile); 

    std::string ss; 

    // allocate string space and set length 
    ss.resize(size); 

    // go back to beginning of file for read 
    rewind(sFile); 

    // read 1*size bytes from sfile into ss 
    fread(&ss[0], 1, size, sFile); 

    // close the file 
    fclose(sFile); 
관련 문제