2010-08-23 3 views
0

tellpseekg 함수에 대한 몇 가지 오해가 있습니다. 예를 들어, 다음 코드를 실행할 때.C++에서 tellp 사용

#include <iostream> 
#include <ostream> 
#include <fstream> 
using namespace std; 
int main(){ 
    string s("in Georgia we are friends to each other"); 
    ofstream out("output.txt"); 
    for (int i=0; i<s.length(); i++){ 
     cout<<"file pointer"<<out.tellp(); 

     out.put(s[i]); 
     cout << " " << s[i] << endl; 
    } 
    out.close(); 
    return 0; 
} 

결과는 다음과 같습니다.

pointer 0 
pointer 1 i 
pointer2 n 
pointer 3 
pointer 4 -g 
........ 

등등. 알다시피, 첫 번째 포인터 0 그것은 포인터 그냥 파일 다음 문자열의 첫 번째 문자를 가리킨다.

이제 다음 코드를 고려하십시오.

#include <fstream> 
using namespace std; 

int main() { 
    long pos; 

    ofstream outfile; 
    outfile.open ("test.txt"); 

    outfile.write ("This is an apple",16); 
    pos = outfile.tellp(); 
    outfile.seekp (pos-7); 
    outfile.write (" sam",4); 

    outfile.close(); 

    return 0; 
} 

결과는 다음과 같습니다

This is a sample 

이 줄, pos = outfile.tellp();, 나는 첫 번째 예에서와 같이 제로에 POS를 얻을 생각합니다. 이 부분에서 outfile.seekp (pos-7)은 무엇을 의미합니까? -7 또는?

+0

출력이 문자열 상수 코드와 일치하지 않습니다. 게시 할 때 전사 오류가있을 수 있습니까? – wallyk

+0

@wallyk : 나를 위해 출력물이 코드와 일치합니다. – bjskishore123

+1

이것은 http://www.cplusplus.com/reference/iostream/ostream/tellp/의 동일한 예제입니다. – Chubsdad

답변

2

tellp는 put 포인터의 현재 위치를 제공합니다. outfile.seekp (pos-7) 문은 put 포인터를 현재 위치에서 7 바이트 뒤로 이동합니다. 예에서 "This is an apple"문자열을 가리키고 있습니다 pos-7을 사용하면 은 'n'문자가있는 위치로갑니다. 거기에서 "sam"문자열을 덮어 씁니다. , tellp는 후에 넣어 포인터의 위치를 ​​가져 오는 데 사용되는이 예에서

: 그래서 결과 문자열은

3

예는 같은 페이지에서 here

입니다 "이것은 샘플입니다"가 쓰기 작업. 포인터는 그 위치에서 파일을 수정하기 위해 7 문자 뒤로 이동하므로 파일의 최종 내용은 다음과 같아야합니다. 이것은 샘플입니다