2010-04-15 5 views
2

C 언어를 사용하여 파일에서 알 수없는 문자 수를 계산하는 쉬운 방법을 찾고 있습니다. 당신의 도움이C 언어의 파일에서 알 수없는 문자 수를 계산합니다.

+0

파일의 크기를 알고 싶습니까? 아니면 얼마나 많은 다른 문자가 파일에 있는지 알고 싶습니까? –

+0

* 알 수 없음 *? 컴파일 타임에 알려지지 않은 것을 의미합니까? – Jacob

+1

와이드 문자가 포함 되나요? – Tom

답변

2

편집 : 당신은 아마이 아래의 답변을 읽고 싶어.

읽기 작업 결과를 EOF (파일 끝)과 비교하여 파일 끝까지 문자를 계속 읽을 수 있습니다. 한 번에 하나씩 처리하면 다른 통계도 수집 할 수 있습니다.

char nextChar = getc(yourFilePointer); 
int numCharacters = 0; 

while (nextChar != EOF) { 
    //Do something else, like collect statistics 
    numCharacters++; 
    nextChar = getc(yourFilePointer); 
} 
+0

덕분에 많은 도움을 얻었습니다. 감사합니다! –

8

POSIX 및 방법 (당신이 원하는 아마 무엇을) 감사 :

off_t get_file_length(FILE *file) { 
    fpos_t position; // fpos_t may be a struct and store multibyte info 
    off_t length; // off_t is integral type, perhaps long long 

    fgetpos(file, &position); // save previous position in file 

    fseeko(file, 0, SEEK_END); // seek to end 
    length = ftello(file); // determine offset of end 

    fsetpos(file, &position); // restore position 

    return length; 
} 

표준 C의 방법은 (학자 연하기) :

long get_file_length(FILE *file) { 
    fpos_t position; // fpos_t may be a struct and store multibyte info 
    long length; // break support for large files on 32-bit systems 

    fgetpos(file, &position); // save previous position in file 

    if (fseek(file, 0, SEEK_END) // seek to end 
     || (length = ftell(file)) == -1) { // determine offset of end 
     perror("Finding file length"); // handle overflow 
    } 

    fsetpos(file, &position); // restore position 

    return length; 
} 

당신의 수를 알고 싶다면 멀티 바이트 문자를 사용하려면 예 : fgetwc으로 전체 파일을 읽어야합니다.

+0

'fsetpos()'를 사용하는 대신'rewind()'가 좀 더 친근하다. – duck

1

이 당신이 파일의 크기를 찾고 있다면 당신은

while (fgetc(file_handler)!=EOF) 
{ 
//test condition here if neccesary. 
    count++; 
} 

일부 문자를 계산 (예를 들어, 인쇄 가능한 문자)해야하는 경우 시작 가야의 fseek과/ftell이 솔루션은 적은 것 같다 비싼 syscall.

+1

꽤 많은 시간이 걸린다. –

+0

예, 그렇습니다. :(:( – Tom

5
FILE *source = fopen("File.txt", "r"); 
fseek(source, 0, SEEK_END); 
int byteCount = ftell(source); 
fclose(source); 
2
/* wc is used to store the result */ 
long wc; 

/* Open your file */ 
FILE * fd = fopen("myfile", "r"); 

/* Jump to its end */ 
fseek(fd, 0, SEEK_END); 

/* Retrieve current position in the file, expressed in bytes from the start */ 
wc = ftell(fd); 

/* close your file */ 
fclose(fd); 
+1

'fd'는 파일 설명자를위한 좋은 이름입니다. int가됩니다. – Potatoswatter

관련 문제