Note that there are some explanatory texts on larger screens.

plurals
  1. POFile input into array by line as string
    primarykey
    data
    text
    <p>Purpose: program to shuffle the lines of a text file</p> <ul> <li><p>Read the file into an array</p></li> <li><p>Count lines and maximum length</p></li> <li><p>Compute maximum width for array</p></li> <li><p>Get file pointer to the beginning</p></li> </ul> <p>These are what I'm trying to do in the first part of the program to give you some perspective. I'm not exactly sure what is meant by "Get file pointer to the beginning". However, my current problem is error reading the lines into an array as strings.</p> <p>Updated code that seg. faults when I go to print shuffled array.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;time.h&gt; // 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) &gt; 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 &lt; lineCount; x++) printf("%2d %s\n", x, lineArray[x]); // Shuffle array srand( (unsigned int) time(NULL)); for (x = lineCount - 1; x &gt;= 0; x--){ i = (int) rand() % lineCount; temp = lineArray[x]; lineArray[x] = lineArray[i]; lineArray[i] = temp; } printf("\nShuffled Array\n"); for (x = 0; x &lt; lineCount; x++) printf("%2d %s\n", x, lineArray[x]); // free allocated memory for (x = 0; x &lt; lineCount; x++) free(lineArray[x]); free(lineArray); fclose(file); return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload