看板 C_and_CPP 關於我們 聯絡資訊
感謝各位的回答。 我後來還是用了strtok來做。 大概把我想要的樣子都弄出來了。 感想:1. 程式語言很多東西不自己實際演練過還真的不會了解。 2. pointer真的是很好玩的東西,有它在我就不會想去玩Java了。 程式碼更新在此: https://gist.github.com/gnitnaw/11ad7e7a98e4ebc8601f #include <stdio.h> #include <stdlib.h> #include <string.h> #define SIZE 256 #define NITEM 15 int getData(char* line, char** t); void outputResult(FILE *fout, char** title, char** t, int N); int main(void) { char s; int i, j, N; char **t = (char**)malloc(sizeof(char*)*NITEM); char **title = (char**)malloc(sizeof(char*)*NITEM); char* line = (char*)malloc(sizeof(char)*SIZE); FILE *fp = fopen("Example_table.txt", "r"); FILE *fout = fopen("output.txt", "a"); if (!fp) { perror("Error! Cannot find the file"); exit(1); } if (!fout) { perror("Error! Cannot create the file"); exit(2); } fgets(line,SIZE,fp); N = getData(line,t); for (i=0; i<N; ++i) { title[i] = malloc(sizeof(t[i])); strcpy(title[i], t[i]); } while(!feof(fp)) { fgets(line,SIZE,fp); j = getData(line, t); if (j<=1) continue; outputResult(stdout,title,t,j); outputResult(fout,title,t,j); } free(line); free(title); fclose(fp); fclose(fout); free(t); return 0; } int getData(char* line, char** t) { int item=0; char *c = strtok(line,"\n"); c = strtok(line,"\t"); t[item++] = c; while (c != NULL && item < NITEM) { c = strtok(NULL,"\t"); if (c!= NULL) t[item++] = c; } return item; } void outputResult(FILE *fout, char** title, char** t, int N) { int i, a; char *b; for (i=0; i<N;++i) { fprintf(fout, "%s : %s ", title[i], t[i]); if (i!=N-1) fprintf(fout, ", "); } fputc('\n',fout); free(b); } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 90.41.134.196 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1434133027.A.1D1.html
arthur104: line:34,76有問題吧! 然後strcpy -> 安全些, 然後 06/13 07:55
arthur104: 檔案有機會開了沒關,最後是malloc你不能保證一定成功。 06/13 07:56
arthur104: 都用define了,有些malloc其實不需要 06/13 08:02
wtchen: line 34我試過沒加不會work.... 06/13 20:34
wtchen: 有些malloc不需要是真的(說真的也只是想多練習pointer) 06/13 20:35
arthur104: title[i]的size會是錯的吧 06/14 00:32
arthur104: 沒加當然不會動@@ 06/14 00:33
anyoiuo: 70, 76行刪了吧! 06/15 14:08
anyoiuo: title[i]有malloc但沒有free, 所以Memory leak! 06/15 14:36
anyoiuo: 然後就arthur大大提到的size, 不要用sizeof用strlen + 1 06/15 14:41
wtchen: 感謝,已修正,真的得多練習coding... 06/19 17:45