fork download
  1. #include <stdio.h>
  2. #include <malloc.h>
  3. #include <stdlib.h>
  4. int main()
  5. {
  6. FILE *fp;
  7. char ***ch;
  8. int n,m, i,j; // char 最多到 128, 改成 int 可應付大數字
  9. char line[10];
  10. if((fp=fopen("水果.txt", "r"))==NULL)
  11. {
  12. printf("無法開啟檔案");
  13. return 1; //exit(1);
  14. }
  15.  
  16. //(比如說我輸入3,出現三個水果名字直到程式結束)
  17. printf("請輸入每行水果個數 M: ");
  18. scanf("%d", &m);
  19. for(n=0; NULL != (fgets(line, sizeof(line), fp)); n++); // 讀總共有個水果 n
  20. fseek(fp, 0, SEEK_SET); // 重回檔頭
  21. n /= m; //共有幾行
  22.  
  23. ch = (char***) malloc(sizeof(char**) * n);
  24. for (i = 0; i < n; i++) {
  25. ch[i] = (char**) malloc(sizeof(char*) * m);
  26. for (j = 0; j < m; ++j)
  27. ch[i][j] = (char*) malloc(sizeof(char)*5);
  28. }
  29.  
  30. for (i = 0; i < n; i++){
  31. for (j = 0; j < m; j++) {
  32. fscanf(fp, "%s\n", ch[i][j]);
  33. }}
  34. fclose(fp);
  35.  
  36. for (i = 0; i < n; i++) {
  37. for (j = 0; j < m; ++j) printf("%s ", ch[i][j]);
  38. printf("\n");
  39. }
  40.  
  41. // free
  42. for (i = 0; i < n; i++) {
  43. for (j = 0; j < m; ++j) free(ch[i][j]);
  44. free(ch[i]);
  45. }
  46. free(ch);
  47.  
  48. system("pause");
  49. return 0;
  50. }
Runtime error #stdin #stdout 0s 2380KB
stdin
Standard input is empty
stdout
無法開啟檔案