K&R exercise 1-23

845 views Asked by At

I have two questions related to the titular exercise, from The C Programming Language. I'm sure that they've both been answered before, so either a direct answer or a link to a previous post (I couldn't find any) would be appreciated.

The exercise itself is to write a C program that removes comments from C code.

  1. I've seen lots of examples of this program, but I can't figure out how to test it. They all use getchar() to "acquire" the code that they're going to edit, but I can't figure out how to tell the program to read another file, rather than to just wait for input from the command line. I tried "./a.out program_to_edit.c", but that didn't work. Alternatively, if there's an easy way to create a string out of blocks of text (rather than one character at a time) like in other languages, that would work too.

  2. This question is a bit more general. I'm confused about how escape characters work when reading C source code with getchar(). If I'm viewing a .c file in TextEdit, I see "\t", but if I compiled it and printed that out, it would come out as a tab character. Does that mean that the .c file contains '\\' and 't' and the compiler combines them, or is it something else entirely? What will getchar() return if I use it to read through that file?

Thanks.

2

There are 2 answers

7
dlask On BEST ANSWER
  1. Redirect standard input: ./a.out < program_to_edit.
  2. Escaped representations exist only in source code. Compiler converts them to the appropriate characters.
2
EvilTeach On

For the first part of your question, you read a file something like this. You should find examples of this in "The Book."

#include <stdio.h>

int main(void)
{
    FILE *fp = fopen("Some_file.txt","rt");
    if (fp != NULL)
    {
        int c = fgetc(fp);
        while (c != EOF)
        {
            /* Do something with c */
        }

        fclose(fp);
    }
    else
    {
        printf("Can't open the file?\n");
    }

    return 0;
}

For the second part of your question, the backslash is an indicator that the backslash and the next characters get replaced by something.

  • /t gets replaced by (char) 9, which is the ascii tab character.
  • /a gets replaced by (char) 7, which is an audiable bell
  • /n gets replaced by (char) 10 on unix systems, and (char)13, (char) 10 on dos systems.

Do some rereading. It's in "The Book."

Welcome to Stack Overflow.