The object of my assignment is to read data from a file, capitalize the first letter of all the names within the file and rewrite the file. Simple enough right?
Just one small problem. The file we have to use has a title. It looks like this:
ID FIRSTNAME LASTNAME
10 john doe
20 mary jane
30 jim smith
This ID FIRSTNAME LASTNAME bit here messes up my file reading. I need to know how to read a file from whatever line I want. My code is as follows:
Code:
#include <stdio.h>
struct employee
{
char firstname[40];
char lastname[40];
int id;
};
typedef struct employee Employee;
Employee e[3];
void PrintEmployeeRecord();
void SaveEmployeeRecord();
//void Capitalize(const Employee e[]);
int main ()
{
int i=0, j =0, r=0, c=0;
Employee e[3];
FILE *file;
file = fopen("employee.dat", "r");// open file
if(file ==NULL){
printf("Cannot create file");//initiate check
return;
}
for (i=0; i<3; i++)
{
fscanf(file,"%d", &e[i].id);
fscanf(file,"%s", e[i].firstname);
fscanf(file,"%s", e[i].lastname);
}
fclose(file); //close file
PrintEmployeeRecord();
//Capitalize(e);
PrintEmployeeRecord();
SaveEmployeeRecord(e);
}
//END MAIN FUNCTION
//purpose: Save employee record to file
//input: array of 3 employee data
//output: file with 3 employee data
void SaveEmployeeRecord(const Employee e[])
{
int i;
FILE *file;
file = fopen("employee.dat", "w"); // open file
if(file ==NULL){
printf("Cannot create file");//initiate check
return;
}
fprintf(file, "ID FIRSTNAME LASTNAME\n"); // print starter data
for (i=0; i<3; i++)
{
fprintf(file, "%d %s %s \n", e[i].id, e[i].firstname, e[i].lastname); //print file data
}
printf("\n Written to file! \n");
fclose(file);// close file
}
//purpose: Print Employee data
//input: array of 3 employee data
//output: 3 employee data printed to screen
void PrintEmployeeRecord()
{
int i;
for (i=0; i<3; i++);
{
printf("%d %s %s \n", e[i].id, e[i].firstname, e[i].lastname);
}
}
Since I haven't been able to properly read the file, I therefore haven't written my capitalize function (hence why it's commented out) but I suspect that I'll simply be using toupper(); in order to do this. (if this isn't the right way to go, please tell me)
Can someone help me?