Question

I want to count the number of letters inside a file. I've already tried writting the file using Windows and Linux test editors, but both give the same value(7). The file have 5 chars('P','2','\n','#','\n'), why does ftell return the value 7 and not 5?

int main(void){
    unsigned char *px=NULL;
        int c=0,size_px;
    FILE *arq;
    arq = fopen("test.txt","rb"); 
        px = (unsigned char*) malloc(100*sizeof(unsigned char));
        fseek(arq,0,SEEK_END); // go to the end of file
        size_px = ftell(arq); //count the letters
        fseek(arq,0,SEEK_SET);  // return to the begin of file
        fread(px,sizeof(unsigned char),size_px,arq);
        printf("|%s| QTY:|%d|",px,size_px);
}

Ps: Even if a i change from 'rb' to 'r' mode it continues giving the answear 7, although in the second mode(r) it prints some garbage. The file was saved using Notepad++ as test.txt. Where there's '\n' it means i pressed the button Enter:

P2\n
#\n
Was it helpful?

Solution

Software applications and operating systems usually represent a newline with one or two control characters:

Systems based on ASCII or a compatible character set use either LF (Line feed, '\n', 0x0A, 10 in decimal) or CR (Carriage return, '\r', 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, '\r\n', 0x0D0A).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top