another C programming question

Writing a program that requires ctrl-d to be pressed to exit the while loop. It is being run on a UNIX server. How can I do this? Im a C newbie, my best guess so far is to use #define EOF (^d) in the preprocessor directives and then put a statement in the while loop, will this work? If not how?

EOF is already a predefined constant in any C implementation I’ve ever seen (defined in stdio.h).

something like:

char c;
while(c=getch() && (c != EOF)) {
/* Do things with c */
}

or

char buf[256];
while(fgets(buf, sizeof(buf), stdin)) {
/* do things with buf
fgets() returns NULL on EOF */
}

should work for you

Oh, and incidentally,

#define EOF (^d)

wouldn’t work anyway. What I think you meant was

#define EOF “^d”

which wouldn’t work anyway :slight_smile: “^d” is just what the console displays (since you can ‘make’ an EOF with CTRL-D), EOF itself is actually -1

Thanks Teletron, your always helpful on my comp nerd questions. I don’t know what I was thinking, as I said I am a C newbie, my book just looked like I could use EOF for this and change -1 to something I wanted to exit the program (I’m all confused).

This won’t actually work.

EOF is defined to be -1 (Actually, I don’t have my copy of the C standard close at hand and can’t remember whether it is defined to be -1 or just a negative integral constant, but for the purpose of this message it doesn’t really matter) , which is out of range of a char. The EOF would be truncated to fit in a char, and then may (depending on whether chars are signed or unsigned (which is implementation defined)) not match EOF due to sign extension. To avoid this problem, use an int instead.

The following example copies standard in to standard out.



int c;
while ((c = getchar()) != EOF) {
     putchar(c);
}


For cw, the ^D is somewhat of a red herring. On a UNIX system, a ^d on a tty generally means end of file (the actual character can be changed with the stty command), On DOS it’s ^Z. In both cases, the ^D or ^Z are never read by your program.

This is what I get for posting late after having a few beers and not checking my work :slight_smile: I can’t even remember the last time I wrote something that used something like this, I stand corrected, sir. :smack:

Well, as John pointed out, I can be wrong :slight_smile: But if I may, you need to get a copy of K&R’s “The C Programming Language”, if you don’t have one already. No C programmer should be without it. It’s not very thick, and it’s been out for ages, so I imagine you could get a pretty cheap copy.