there were many problems with the code.
the following compiles cleanly
However, I have not run it.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define MAX_LINE_LENGTH (100)
void cleanup(char **, int);
int main()
{
int N = 0; // count of data line in file
FILE *lessonsptr;
if(NULL == (lessonsptr = fopen("lesson.txt", "r")))
{ // then fopen failed
perror("fopen failed for lesson.txt");
exit(EXIT_FAILURE);
}
// implied else, fopen successful
// get count of following lines
if(1 != fscanf(lessonsptr, " %d \n", &N))
{ // then, fscanf for line count failed
perror("fscanf failed for line count");
fclose(lessonsptr);
exit(EXIT_FAILURE);
}
// implied else, fscanf for line count successful
char **lessons = NULL;
int i = 0; // loop counter
if(NULL == (lessons = malloc(N*sizeof(char*))))
{ // then malloc failed
perror("malloc failed for lessons");
fclose(lessonsptr);
exit(EXIT_FAILURE);
}
// implied else, malloc successful for lessons
// set all lessons[] to NULL
memset(lessons, 0x00, (N*sizeof(char*)));
for(i=0; i< N; i++)
{
if(NULL == (lessons[i] = malloc(MAX_LINE_LENGTH)))
{ // then, malloc failed
perror("malloc failed for lessons[]");
fclose(lessonsptr);
cleanup(lessons, N);
exit(EXIT_FAILURE);
}
// implied else, malloc successful for lessons[i]
// clear the malloc'd memory
memset(lessons[i], 0x00, MAX_LINE_LENGTH);
}
char str[MAX_LINE_LENGTH] = {'\0'};
for(i = 0; i<N; i++)
{
if(NULL == fgets(str, MAX_LINE_LENGTH, lessonsptr))
{ // then file did not contain enough lines
perror("fgets failed");
fclose(lessonsptr);
cleanup(lessons, N);
exit(EXIT_FAILURE);
}
// implied else, fgets successful
// copy line to where lessons[i] points
memcpy(lessons[i], str, MAX_LINE_LENGTH);
// prep for next input line
memset(str, 0x00, MAX_LINE_LENGTH);
} // end for
fclose(lessonsptr);
cleanup(lessons, N);
return(0);
} // end function: main
void cleanup(char **lessons, int N)
{
int i; // loop counter
for(i=0; i<N; i++)
{
free(lessons[i]);
}
free(lessons);
} // end function: cleanup
如果你的意思是在換行符到字符串讀取,那麼就讓它,事後刪除換行符 –
此外,您還需要爲每節課分配空間,從'str'複製字符串到這個新空間。現在,lesson數組中的所有條目都會以'str'結尾,它只是'str'數組的地址,它只包含從文件讀取的最後一課。 –
而且你不讀取N個條目,但讀取的文件數量與文件包含的數量相同。如果超過100,你將走出課程陣列的末尾......並且你不檢查fopen的結果以查看它是否工作等等。 –