P
Peter Blues
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.
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;
char file_name[80];
FILE *outstream;
printf("File Name: \n");
scanf("%79s", file_name);
if((outstream = fopen(file_name, "w")) == NULL) {
fprintf(stderr, "open %s for writing failed ", file_name);
perror("because");
return 1;
}
while((fd = getchar()) != EOF)
fputc(fd, outstream);
fclose(outstream);
return 0;
}
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.
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;
char file_name[80];
FILE *outstream;
printf("File Name: \n");
scanf("%79s", file_name);
if((outstream = fopen(file_name, "w")) == NULL) {
fprintf(stderr, "open %s for writing failed ", file_name);
perror("because");
return 1;
}
while((fd = getchar()) != EOF)
fputc(fd, outstream);
fclose(outstream);
return 0;
}