Here's the important code:
struct line {
char *linetext;
int linenumber;
struct line *nextline;
};
#define NEXTLINE (*((*lineptr).nextline))
int *numsOfChars( FILE *fp ){
int numLines = linecount( fp );
int *lines = (int *) malloc( sizeof(int) ); // Declare int array. Must use malloc because
wchar_t ch; // the address is returned by the function.
for( int j = 0; j < numLines; j++ ){
lines[j] = 0;
while( (ch = fgetc( fp )) != '\n' ){ // For each line n, this goes until the nth
lines[j]++; // newline, effectively counting the characters
} // in the nth line until the newline.
}
rewind( fp );
return lines;
}
Most importantly:
// This function reads another line and stores it in the linked list.
// Parameters: lineptr - pointer to the current line, numchars - array of character counts for each line, fp - file pointer
struct line *readLine( struct line *lineptr, int *numchars, FILE *fp ){
// line number for next line
int nextLineNum = (*lineptr).linenumber + 1;
// allocate memory for next line
(*lineptr).nextline = (struct line *) malloc( sizeof(struct line) );
// set line number
NEXTLINE.linenumber = nextLineNum;
// string to read the line from the file into
char *linec = (char *) malloc( sizeof(char) * (numchars[nextLineNum] + 1) );
// read the line of the file into the string
fgets( linec, (numchars[nextLineNum] + 1), fp );
// const because strcpy takes a const as its second parameter
const char *line2c = linec;
// dynamically allocate NEXTLINE.linetext so it can be copied to
NEXTLINE.linetext = (char *) malloc( sizeof(char) * (numchars[nextLineNum] + 1) );
// copy to linetext
strcpy( NEXTLINE.linetext, line2c );
free( linec );
return (*lineptr).nextline;
}
Without comments, if that makes it easier to read:
struct line *readLine( struct line *lineptr, int *numchars, FILE *fp ){
int nextLineNum = (*lineptr).linenumber + 1;
(*lineptr).nextline = (struct line *) malloc( sizeof(struct line) );
NEXTLINE.linenumber = nextLineNum;
char *linec = (char *) malloc( sizeof(char) * (numchars[nextLineNum] + 1) );
fgets( linec, (numchars[nextLineNum] + 1), fp );
const char *line2c = linec;
NEXTLINE.linetext = (char *) malloc( sizeof(char) * (numchars[nextLineNum] + 1) );
strcpy( NEXTLINE.linetext, line2c );
free( linec );
return (*lineptr).nextline;
}
How I called it:
curline = readLine( curline, numchars, fp );This works fine for the first few lines, but after I get to about the fifth or sixth one, the linked list gets really huge and the program runs out of memory, resulting in a bus error. Is there any way I can fix this?


Sign In
Create Account

This topic is locked

Back to top









