麻烦纠个错谢谢
Write a program which reads lines from a text file into a dynamically allocated array.Program may use a static limit for line length.
Hint: First open the file then read (and discard) all lines to count
how many lines there are in the file. Then reopen the file to really read the data.
程序代码:
#include <stdio.h> #include <stdlib.h> #include <conio.h> #include <string.h> #define MY_FILENAME "data.txt" #define FILESIZE 50 #define LINE_LENGTH 255 int main() { FILE *fp; int h=0; int i; char c; char *data[LINE_LENGTH+1]; char cur[LINE_LENGTH+1]; char filename[FILESIZE]="data.txt",fileinput[FILESIZE],*fileptr;/*share the same file with no.30,so use the address form..*/ printf("Please enter a filename!\n"); scanf("%s",fileinput); fileptr=strstr(filename,fileinput); if (fileptr) { if ((fp=fopen("data.txt","r"))==NULL) { printf("Cannot open file strike any key exit!"); getch(); exit(1); } else while (!feof(fp)) { if (fgetc(fp)=='\n') h++; else; { c=getc(fp); if (c==EOF) { h++; break; } } } printf("%d\n",h); fclose(fp); } if ((fp=fopen(MY_FILENAME, "r")) == NULL) { printf("freopen error!\n"); exit(1); } else { printf("read successfully\n"); fseek(fp,0,SEEK_SET); for (i=0;i<h ;i++ ) { if (fgets(cur,LINE_LENGTH,fp)) { data[i]=(char *)malloc(strlen(cur)*sizeof(char)); if (data[i]==NULL) { printf("malloc error!\n"); exit(1); } strcpy(data[i],cur); printf("%s",data[i]); free(data[i]); } } } fclose(fp); return 0; } data.txt的内容就是题干 运行结果在下面图片里 只显示了两行 然后就死机 调试没有问题
[ 本帖最后由 Timber 于 2010-5-16 18:01 编辑 ]