Search code examples
cfilewhile-loopstdio

Why does this loop not print the same value continuously?


I am trying to understand some C code I've stumbled across. For the record, the code does exactly what it's supposed to except for the print line I added. It takes all of the contents from the inputFile.txt, and replaces the J's with X's, and writes it to the outputFile.txt.

int main(void) {
    int fd_to_read = open("inputFile.txt", O_RDONLY);
    int fd_to_write = open("outputFile.txt", O_WRONLY | O_CREAT);

    char c;
    int bytes;
    while ((bytes = read(fd_to_read, &c, sizeof(c))) > 0) {
        if (c == 'J') {
            c = 'X';
        }
        write(fd_to_write, &c, sizeof(c));
        //I added this and it doesn't work.
        printf(&c);
    }
    close(fd_to_read);
}

When I first saw this, I expected the while loop to print the first character from the file over and over again. I understand that the read() function will be executed until it is >0, but I assumed that in order for it to change position in the file the memory address pointed to by c would have to increment by something, possibly the sizeof(c), but nothing appears to increment and it just moves on to the next letter in the file. My next assumption is that read() handles that on it's own, but when I went to print the contents of &c I got close to what I expected, which was a ton of garbage, since it was just printing random things from memory essentially.

So, two questions really.

  1. How is the &c that is written to the outputFile.txt write to that correctly without incrementing the address of c?

  2. How would I just print the individual characters from the file without all the garbage since print(&c) added all the garbage after each char?


Solution

  • Ok two things.

    (1) char c does not need to be incremented because it is serving like the output to the read fn.

    (2) the read and write fn's automatically increment their respective file descriptors.

    The file descriptors (fd_to_read, fd_to_write) represent a location in the file, not char c.

    Read about it in the man pages: https://linux.die.net/man/3/read https://linux.die.net/man/3/write