I am trying to read information from 2 CSV files: import.txt and ss_data.txt (contents shown below). Import.txt has the data in the following order: employee id, name, address. I want to create a new file containing the social security numbers from ss_data.txt between the employee name and address. I would appreciate any advice on how to accomplish this, the closest I have come is appending the new file after the original.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define BSIZE 12
#define STRSIZE 70
#define MAXEMP 25
typedef struct employee{
int empID;
char name[STRSIZE];
int ssNumber;
char address[STRSIZE];
} employee;
typedef struct {
int empID;
char ssn[BSIZE];
} ssdef;
typedef employee *empPtr;
int main(void)
{
// Define variables.
FILE *inFile, *newFile, *outFile;
char str[STRSIZE];
int index = 0;
int i = 0;
// new employee
employee newEmp[MAXEMP];
ssdef newSS;
// Open files.
inFile = fopen("import.txt", "r");
newFile = fopen("ss_data.txt", "r");
outFile = fopen("updated.txt", "w");
// Check files opened.
if(inFile == NULL || newFile == NULL || outFile == NULL)
{
puts("Could not open files");
exit(0);
}
while(fgets(str, STRSIZE, inFile) != NULL)
{
memset(&newEmp[index], '\0', sizeof(employee));
sscanf(str, "%6u,%[^,],%[^\n\r]", &newEmp[index].empID, newEmp[index].name, newEmp[index].address);
// printf("%u.%s.%s\n", newEmp[index].empID, newEmp[index].name, newEmp[index].address);
index++;
}
while(fgets(str, STRSIZE, newFile) != NULL)
{
memset(&newSS, '\0', sizeof(newSS));
str[strlen(str)-1] = '\0';
sscanf(str, "%6u%s", &newSS.empID, newSS.ssn);
//printf("%u.%s\n", newSS.empID, newSS.ssn);
for(i=0;i<index;i++)
{
if(newEmp[i].empID == newSS.empID)
{
fprintf(outFile,"%u,%s,%s,\"%s\"\n", newEmp[i].empID, newEmp[i].name, newSS.ssn, newEmp[i].address);
break;
}
}
}
printf("Copied");
fclose(inFile);
fclose(newFile);
fclose(outFile);
return 0;
}
import.txt:
289383,Estefana Lewey,9940 Ohio Drv, 85021
930886,Burl Livermore,226 Amherst, 08330
692777,Lannie Crisler,8143 Woods Drv, 20901
636915,Zena Hoke,82 Roehampton St, 47905
747793,Vicente Clevenger,9954 San Carlos St., 55016
238335,Lidia Janes,348 Depot Ave, 29576
885386,Claire Paladino,587 Front Ave, 32703
760492,Leland Stillson,9793 Boston Lane, 08610
516649,Wes Althouse,8597 Annadale Drive, 06514
641421,Nadia Gard,218 George Street, 29150
ss_data.txt:
289383,591-82-1520
930886,661-18-3839
692777,590-36-6612
636915,510-92-2741
747793,233-46-1002
238335,512-92-7402
885386,376-74-3432
760492,576-55-8588
516649,002-58-0518
641421,048-14-6428