On Feb 6, 3:14 am, Peter Blues <peterbl...@hotmail.comwrote:
I'm trying to write from keyboard input to a txt file. I don't understand
why the while loop below doesn't achieve this.
I..
1: open the file for writing through FILE pointer outstream
2: I get chars one at a time as ints(ascii) through fd using getchar()
3: Copy from fd to FILE *outstream using fputc()
4: Finally close outstream.
You are a bit confused about what int and ascii is.
I feel the problem lies in step 2 and 3. Can someone please explain
where the following code is wrong.
#include <stdio.h>
int main(void) {
int fd;
'fd' as a name for an int object is a bad name, because 'int fd;' is
commonly used in UNIX programming where fd stands for file descriptor.
char file_name[80];
You could change that to FILENAME_MAX
FILE *outstream;
printf("File Name: \n");
scanf("%79s", file_name);
You read at most 79 characters but the last character of file_name is
not initialized.
Either do file_name[79] = 0; or define file_name as char file_name[80]
= {0};
You also don't check the return value of scanf but I don't think that
is importand for such small code.
(althought if this code is part of a bigger project, I suggest you do
check the return value)
>
if((outstream = fopen(file_name, "w")) == NULL) {
fprintf(stderr, "open %s for writing failed ", file_name);
perror("because");
How about this
fprintf(stderr, "open %s for writing failed because %s\n", file_name,
strerror(errno));
You need to include <string.hfor strerror().
return 1;
It is not portable to return 1 from main.
The portable values are 0, EXIT_SUCCESS and EXIT_FAILURE, again, for a
small snippet it does not matter much.
If it's a bigger project change it.
}
while((fd = getchar()) != EOF)
fputc(fd, outstream);
This seems alright to me.
>
fclose(outstream);
return 0;
}
I believe your problem lies in your confusion about keyboard being
stdin.
stdin is just an input file stream.
C does not define a 'keyboard'. If you expect the above snippet to
capture keystrokes.. then you are out of luck as far as ISO C is
concerned.
You can, however use a system specific function to capture them, which
is off-topic for this newsgroup.
try a newsgroup whose subject is relevant to your system.