So I am supposed to create a function that accomplishes: Purpose: program to shuffle the lines of a text file
- Read the file into an array
- Count lines and maximum length
- Compute maximum width for array
- Get file pointer to the beginning
- Reserve memory for a dynamic array of strings
- Read a line and store in allocated memory
- Turn the \n into \0
- Print lines from array (test)
- Shuffle array
- Print lines from array (test)
- Free memory and close file
(just to give some background)
However, when I go to print the shuffled array, I get segmentation faults. Occasionally, it prints one or two of the strings, but sometimes It just says "Shuffled Array" and then I get a segmentation fault. Any ideas?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
// Accepts: command line input
// Returns: 0 if no error
int main(int argc, char *argv[] ){
int x = 0, i, lineCount = 0, maxLen = 0;
char line[500], temp;
FILE *file = fopen( argv[1], "r" );
// check if file exists
if (file == NULL){
printf("Cannot open file\n");
return 1;
}
// Gets lines, max length of string
while (fgets(line, sizeof(line), file) != NULL){
lineCount++;
if (strlen(line) > maxLen)
maxLen = strlen(line);
}
rewind(file);
char *lineArray[lineCount];
while (fgets(line, sizeof(line), file) != NULL) {
lineArray[x] = malloc(strlen(line));
if (lineArray[x] == NULL){
printf("A memory error occurred.\n");
return(1);
}
strcpy(lineArray[x], line);
// change \n to \0
lineArray[x][strlen(lineArray[x])-1] = '\0';
x++;
}
printf("File %s has %d lines with maximum length of %d characters\n",
argv[1], lineCount, maxLen);
printf("Original Array\n");
for (x = 0; x < lineCount; x++)
printf("%2d %s\n", x, lineArray[x]);
// Shuffle array
srand( (unsigned int) time(NULL));
for (x = lineCount - 1; x >= 0; x--){
i = (int) rand() % lineCount;
temp = lineArray[x];
lineArray[x] = lineArray[i];
lineArray[i] = temp;
}
printf("\nShuffled Array\n");
for (x = 0; x < lineCount; x++)
printf("%2d %s\n", x, lineArray[x]);
// free allocated memory
for (x = 0; x < lineCount; x++)
free(lineArray[x]);
free(lineArray);
fclose(file);
return 0;
}