fork download
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<string.h>
  4. #include<ctype.h>
  5. #define SIZE 40
  6.  
  7. int counterline(FILE *Ptr) { //計算過濾檔行數
  8. char buffer[SIZE];
  9. int counter = 0;
  10.  
  11. while (fgets(buffer, SIZE, Ptr) != NULL) { //一次一行,有讀到字則counter+1
  12. counter++;
  13. }
  14.  
  15. return counter;
  16. }
  17.  
  18. void filter(FILE *Ptr, char **input, int times) { //讀取過濾檔
  19.  
  20. for (int i = 1; i <= times; i++) { //times為行數
  21.  
  22. char buffer[SIZE];
  23. fgets(buffer, SIZE, Ptr);
  24. int length = strlen(buffer); //讀取字串長
  25.  
  26. for (int j = 1; j <= length; j++) {
  27. while (isspace(buffer[j - 1])) { //處理buffer中不為英數的字
  28. for (int k = j; k <= length; k++) {
  29. buffer[k - 1] = buffer[k];
  30. }
  31. length--;
  32. }
  33. }
  34.  
  35. input[i - 1] = (char*)malloc(sizeof(char)*(length + 1));
  36. strcpy(input[i - 1], buffer); //buffer轉存input
  37. }
  38. }
  39.  
  40. void write(FILE *fPtr, char content[]) {
  41. for (int index = 0; content[index] != '\0'; index++) {
  42. fputc(content[index], fPtr);
  43. }
  44. fputc('\n', fPtr);
  45. }
  46.  
  47. FILE* open(char fileName[], char type[]) {
  48. FILE *fPtr = fopen(fileName, type);
  49. if (fPtr == NULL) {
  50. printf("The file opened error.\n");
  51. exit(1);
  52. }
  53. return fPtr;
  54. }
  55.  
  56. void fill(FILE *Ptr, char ** filter, int times) {
  57. char ch;
  58. char buffer[20];
  59. long counter = 0;
  60. int c = 0;
  61.  
  62.  
  63. while ((ch = fgetc(Ptr)) != EOF) {
  64. if (!isspace(ch)) {
  65.  
  66. buffer[c] = ch;
  67. c++;
  68. }
  69. else {
  70. buffer[c] = '\0';
  71. for (int i = 1; i <= times; i++) {
  72. if (strcmp(buffer, filter[i - 1]) == 0) {
  73. fseek(Ptr, counter, SEEK_SET);
  74. for (int i = 1; i <= c + 1; i++) {
  75. fputc(' ', Ptr);
  76. }
  77. }
  78. }
  79. counter += c; // <---待修
  80. c = 0;
  81. buffer[c] = '\0';
  82. }
  83.  
  84. }
  85. }
  86.  
  87. int main(int argc, char *argv[]) {
  88. char **input; //二維動態陣列
  89. FILE *inputPtr = open(argv[1], "r");
  90.  
  91. int line = counterline(inputPtr);
  92. rewind(inputPtr);
  93.  
  94. input = (char **)malloc(sizeof(char*)*line);
  95. filter(inputPtr, input, line);
  96.  
  97. FILE *inPtr = open(argv[2], "r+");
  98. fill(inPtr, input, line);
  99.  
  100.  
  101.  
  102.  
  103. fclose(inputPtr);
  104. free(input);
  105. system("pause");
  106. }
Runtime error #stdin #stdout 0s 2244KB
stdin
Standard input is empty
stdout
The file opened error.