
Originally Posted by
jimblumberg
Please show the file contents you are trying to "seek" through.
Did your colleague use binary methods to write the file (like fwrite())?
Trying to seek in a text file is very problematic. Text files are usually not suitable for "random searching".
I'd start by reading the file provided by you colleague one record at time, storing the record in an array in memory. Then once you have read the entire file step through the array to find the desired record. Edit the record, then re-write the file with the modified data. Trying to "replace" content in the middle of a file will usually not work properly ( even you you use the proper file open mode).
Here's a version i've simplified for my testing:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
struct studentdata{
int student_number;
char student_name[40];
int student_id;
char student_address[60];
int phone_number;
};
void main(){
FILE *p;
struct studentdata insert;
int edit_student;
struct studentdata change;
p = fopen("students.txt","a");
printf("Insert student\n\n ");
printf("Student Number: ");
scanf("%d", &insert.student_number);
printf("Student Name: ");
scanf("%s", &insert.student_name);
printf("Student ID: ");
scanf("%d", &insert.student_id);
printf("Address: ");
scanf("%s", &insert.student_address);
printf("Phone Number: ");
scanf("%d", &insert.phone_number);
printf("\tData saved sucessfully.\n");
fwrite(&insert, sizeof(struct studentdata), 1, p);
fclose(p);
p = fopen("students.txt","r+");
while(fread(&change,sizeof(struct studentdata),1,p)){
printf("Student Number: %d\n", change.student_number);
printf("Student Name: %s\n", change.student_name);
printf("Student ID: %d\n", change.student_id);
printf("Address: %s\n", change.student_address);
printf("Phone Number: %d\n\n\n", change.phone_number);
}
printf("Please input the student number you want to edit:");
scanf("%d",&edit_student);
void rewind(p);
fseek(p,sizeof(struct fornecedor)*(id_fornecedor-1),SEEK_SET);
scanf("%s", &edit.student_name);
printf("Student ID: ");
scanf("%d", &edit.student_id);
printf("Address: ");
scanf("%s", &edit.student_address);
printf("Phone Number: ");
scanf("%d", &edit.phone_number);
}
I know it still needs a lot of tweaking, but if i'm not even getting the "simple" part working, the other part is the next step