Hello,
I'm taking a C class, and stuck on an assignment. I know the prog has a few more kinks in it, but I've hit a wall.
In the func read_into_array(), **line_array is supposed to get filled by values read in from a file. When I do a printf of it, each element has the last value read in from the file!!
The assignment is to take lines from a file, formatted like this:
Doe,John 85
and sort them by score, with ties broken by name, into another file.
Code:
/* CIS 15BG
* Lab #3
* Due Date: 2/9/10
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "perry.h"
#define BUCKET_SIZE 5
#define LINE_LEN 100
char *name_score_swap(char *score_line);
void main(int argc, char **argv)
{
void checkargs(int numargs, char **args, FILE **fpin, FILE **fpout);
char **read_into_array(FILE **fpin);
void sel_sort_scores(FILE **fpout, char **line_array);
char **line_printer, **line_array;
FILE *fpin, *fpout;
checkargs(argc, argv, &fpin, &fpout);
line_array = read_into_array(&fpin);
sel_sort_scores(&fpout, line_array);
for(line_printer = line_array; *line_printer; line_printer++)
fputs(name_score_swap(*line_printer), fpout);
}
void checkargs(int numargs, char **args, FILE **fpin, FILE **fpout)
{
if(numargs != 3)
{
printf("Usage: %s infile outfile\n", args[0]);
exit(EXIT_FAILURE);
}
*fpin = Fopen(args[1], "r");
*fpout = Fopen(args[2], "w");
}
char **read_into_array(FILE **fpin)
{
char buffer[LINE_LEN + 1], **lineptr, **line_array;
int lines = 0;
int i;
line_array = (char **) Malloc(BUCKET_SIZE * sizeof(char *));
lineptr = line_array;
while(fgets(buffer, LINE_LEN + 1, *fpin))
{
*lineptr = (char *) Malloc((strlen(buffer) + 1) * sizeof(char));
*lineptr = name_score_swap(buffer);
lines++;
if(lines % BUCKET_SIZE == 0)
line_array = (char **) Realloc(line_array,
(BUCKET_SIZE + lines) * sizeof(char *));
lineptr = line_array + lines;
}
*lineptr = '\0';
for(i=0;i<10;i++)
printf("%p\n", line_array[i]);
Fclose(*fpin);
return(line_array);
}
void sel_sort_scores(FILE **fpout, char **line_array)
{
char **mover, **shaker, **temp;
for(mover = line_array, shaker = mover + 1; *mover; mover++)
{
printf("%p", mover);
while(*shaker)
{
if(strcmp(*mover, *shaker))
{
*temp = *mover;
*mover = *shaker;
*shaker = *temp;
}
printf("%d\n", **mover);
shaker++;
}
}
}
char *name_score_swap(char *score_line)
{
char *temp, *ptr;
temp = (char *) Malloc((strlen(score_line) + 1) * sizeof(char));
ptr = strchr(score_line, '\040');
*ptr = '\0';
strcpy(temp, ptr + 1);
strcat(temp, "\040");
strcat(temp, score_line);
return(strcpy(score_line, temp));
}