Write a below source code, save it as "file.1c", and confirm whether it can run properly.
#include <stdio.h> #include <stdlib.h> int main(void) { FILE *fout; int c; if((fout=fopen("file1.txt", "w")) == NULL){ printf("Cannot open output file\n"); exit(1); } printf("Input string\n"); printf("Ctrl-d if you want to exit\n"); while ((c=getchar()) != EOF){ putc(c, fout); } fclose(fout); exit(0); }
(Execution result) $ $ ./a.out Input string Ctrl-d if you want to exit aaaa bbbbbbbbbbbbb cccccc dddddddd eeee $ $ cat file1.txt aaaa bbbbbbbbbbbbb cccccc dddddddd eeee
We want to read strings from "file1.txt" created in Exercise 1, and show them on screen by "printf()". Write a below source code, complement the expression hidden by "******" and save it as "file.2c". Confirm whether it can run properly.
#include <stdio.h> #include <stdlib.h> int main(void) { FILE *fin; char c[256]; if((fin=fopen("file1.txt", "r")) == NULL){ printf("Cannot open input file\n"); exit(1); } printf("Contents of file1.txt:\n"); while (*****************************){ printf("%s",c); } fclose(fin); exit(0); }
(Execution result) $ $ ./a.out Contents of file1.txt: aaaa bbbbbbbbbbbbb cccccc dddddddd eeee $
Write a below source code, save it as "file.3c", and confirm whether it can run properly.
#include <stdio.h> #include <stdlib.h> int main(void) { FILE *fout; int dat; if((fout=fopen("file3.txt", "w")) == NULL){ printf("Cannot open output file\n"); exit(1); } printf("Input integer\n"); printf("Ctrl-d if you want to exit\n"); while (scanf("%d", &dat) != EOF){ fprintf(fout,"%d ",dat); } fclose(fout); exit(0); }
(Execution result) $ $ ./a.out Input integer Ctrl-d if you want to exit 21 78 42 93 76 <- Ctrl-d $ $ cat file3.txt 21 78 42 93 76 $
We want to read data from "file3.txt" created in Exercise 3, and show the values of the data multiplied by 3. Write a below source code, complement the expression hidden by "******" and save it as "file.4c". Confirm whether it can run properly.
#include <stdio.h> #include <stdlib.h> int main(void) { FILE *fin, *fout; int dat; if((fin=fopen("file3.txt", "r")) == NULL){ printf("Cannot open input file\n"); exit(1); } if((fout=fopen("file4.txt", "w")) == NULL){ printf("Cannot open output file\n"); exit(1); } while (****************************){ ******************************** } fclose(fin); fclose(fout); exit(0); }
(Execution result) $ $ ./a.out $ $ cat file4.txt 63 234 126 279 228 $