Reading a shared file

I am making a program that reads in a file from stdin, does something with it and sends it to stdout.

In the order of things, I have a line in my program:

while((c = getchar()) != EOF){

where cis int.

However, the problem is that I want to use this program for ELF executables. And it seems that there should be a byte that represents EOF for ascii files inside the executable, which leads to truncation (correct me if I am wrong here - this is just my hypothesis).

What is an effective general way to do this? I could dig up ELF documents and then just check what happens at the end. That would be useful, but I think it would be better if I could apply this program to any file.

+3
source share
4 answers

- EOF ASCII ( -1).

, stdio.h :

/* End of file character.
   Some things throughout the library rely on this being -1.  */
#ifndef EOF
# define EOF (-1)
#endif
+3

, , open(), close() read(), , , .

+1

.

EOF . c EOF . / c EOF, , /. EOF , - .

, c int

Oh... . , stdin " ", .

FILE *mystream = fopen(filename, "rb");
if (mystream) {
    /* use fgetc() instead of getchar() */
    while((c = fgetc(mystream)) != EOF) {
        /* ... */
    }
    fclose(mystream);
} else {
    /* error */
}
+1

On the getchar (3) man page:

Character values ​​are returned as unsigned char converted to int.

This means that the value of a character read through getchar can never be equal to the value of the integer -1. This little program explains this:

int main(void)
{
        int a;
        unsigned char c = EOF;

        a = (int)c;
        //output: 000000ff - 000000ff - ffffffff
        printf("%08x - %08x - %08x\n", a, c, -1);
        return 0;
}
0
source

All Articles