Printing contents of a file...prints one extra character not present in the file.
Hello,
I'm writing a program that stores records into a file and then these records can be printed out. A last name, first name, and score is stored to be exactly 36 characters long (using leading spaces to pad) making it easier to retrieve specific records. For example, three records stored in the file would like like this: (the underscores are simply to illustrate the distance, they are not in the file itself)
_______lastname_______firstname__90__________lname __________fname_100___________last___________first __60
When printed out, the names are formatted as follows:
lastname, firstname: 90
lname, fname: 100
last, first: 60
However, when I print them out this is what I get:
lastname, firstname: 90
lname, fname: 100$
last, first: 60H
For some reason, for any record after the first, an extra character is added to the end. These characters are not in the file, so I was thinking that the array for some reason wasn't being filled completely, (the array is initialized to size 36 and 36 characters are read from the file using fread) so it was printing out a random character assigned to the 36th array position. Except the character never changes, (always a $ for record 2, H for record 3, l for record 4 if i remember) and I've tried reducing the array size or the number of character read and it's the string that gets altered, the random character always remains. I figure the problem must be in the print_records function (appending seems to work no problem). Anyway here is my print records and appending records code.
Code:
/*
- Prints a single record stored in the file pointed to by ifp.
*/
void print_record(FILE *ifp, int record) {
char record_array[36];
size_t i;
int break_count = 0;
char cur_char;
char prev_char = '\0';
int file_location = 36 * (record - 1);
if(fseek(ifp, file_location, SEEK_SET) != 0)
perror("fseek");
fread(record_array, 1, 36, ifp);
for(i = 0; record_array[i] != '\0'; i++) {
cur_char = record_array[i];
if(cur_char != ' ')
printf("%c", record_array[i]);
else if(cur_char == ' ' && isalpha((int)prev_char)) {
if(break_count == 1)
printf(": ");
else if(break_count == 0) {
printf(", ");
break_count++;
}
}
prev_char = cur_char;
}
printf("\n");
}
/*
- Appends the name portion of a record to the end of the file pointed to by ifp.
*/
void append_records_name(FILE *ifp, char name[]) {
if(fseek(ifp, 0, SEEK_END) != 0)
perror("fseek");
str_lowercase(name);
fprintf(ifp, "%15s", name);
fprintf(ifp, " ");
}
/*
- Appends the score portion of a record to the end of the file pointed to by ifp.
*/
void append_records_score(FILE *ifp, int score) {
if(fseek(ifp, 0, SEEK_END) != 0)
perror("fseek");
fprintf(ifp, "%3d", score);
fprintf(ifp, " ");
}
Any help that can be provided would be much appreciated.