Converting text to a binary file - c

I need to convert a text file of the following format to binary:
The first line contains the number of products in the inventory, The following lines contains:
product name '\t' product price '\t' quantity '\n'
(there can be more than one \t between columns)
For every product the binary output file will contain an int representing the length of the product name, the chars that hold the product name, an int representing the price and an int representing the quantity.
Sample input file:
Asus Zenbook 1000 10
iPhone 5 750 22
Playstation 4 1000 0
I have wrote the following code, and I understood that I'm supposed to see the string in plain text while the integers will show up as gibberish (in binary):
int convertTextToBinary(char *fileName)
{
FILE *pText, *pBinary;
int size, i;
char *currProdName;
int currProdNameLen, currQuantity, currPrice;
if (checkFileExists(fileName) == FALSE)
{
printf("- Given file does not exists!\n");
return ERROR;
}
else
pText = fopen(fileName, "r");
// get the number of products in the inventory
fscanf(pText, "%d", &size);
#ifdef DBG
printf("##DBG Successfuly read &size = %d DBG##\n", size);
#endif
pBinary = fopen(strcat(fileName, ".bin"), "wb");
fwrite(&size, sizeof(int), 1, pBinary);
#ifdef DBG
printf("##DBG Successfuly wrote &size = %d DBG##\n", size);
#endif
for (i = 0; i < size; i++)
{
// get product name and name length
currProdNameLen = getProdName(pText, &currProdName);
#ifdef DBG
printf("##DBG %d Successfuly read &currProdName = %s DBG##\n", i+1, currProdName);
printf("##DBG %d Successfuly read &currProdNameLen = %d DBG##\n", i+1, currProdNameLen);
#endif
// get product price
fscanf(pText, "%d", &currPrice);
printf("##DBG %d Successfuly read &currPrice = %d DBG##\n", i+1, currPrice);
// get product quantity
fscanf(pText, "%d", &currQuantity);
printf("##DBG %d Successfuly read &currQuantity = %d DBG##\n", i+1, currQuantity);
// write data to binary file
fwrite(&currProdNameLen , sizeof(int), 1, pBinary);
fwrite(&currProdName, sizeof(char), currProdNameLen, pBinary);
fwrite(&currPrice, sizeof(int), 1, pBinary);
fwrite(&currQuantity, sizeof(int), 1, pBinary);
free(currProdName);
}
fclose(pText);
fclose(pBinary);
return 1;
}
/* This function checks if a file in a given path exists or not by using fopen with "read" argument */
BOOL checkFileExists(char *fileName)
{
FILE *fp;
fp = fopen(fileName, "r");
// file does not exists
if (fp == NULL)
return FALSE;
// file does exists
else
{
fclose(fp);
return TRUE;
}
}
int getProdName(FILE *fp, char **prodName)
{
int nameLen = 0, offset;
// count the length of the product name
while (fgetc(fp) != '\t')
nameLen++;
// allcoate memory for the product name
*prodName = (char*)malloc(sizeof(char)*nameLen);
//checkalloc(&prodName);
// get the cursor back to the original position
offset = -1 * nameLen;
fseek(fp, offset, SEEK_CUR);
// copy product name from text to string
fgets(*prodName, nameLen, fp);
return strlen(*prodName);
}
But the hell, my output file looks like this:
¨ ּּּּּט ¨ ּּּ¯ ¨ ּּּּּּּּ ּּּ«
¨
Which holds no plain text. I have tried changing the fopen argument from "wb" to "w" but I still get gibberish files. What am I doing wrong?

Here you write the pointer and additional garbage instead of the string it points to:
fwrite(&currProdName, sizeof(char), currProdNameLen, pBinary);
You should use:
fwrite(currProdName, sizeof(char), currProdNameLen, pBinary);
In your version you are passing the pointer to the pointer, but you want to pass the pointer itself.
BTW: In your function getProdName(), you should add an additional character, because you are allocating the exact string lenght, but no room for the 0 Byte at the end. This can also cause problems. Also fgets reads one char less. Check the man page for fgets. Instead of using fgets, you can also use fread because you know the length anyway. No additional parsing needed.
update
Change this:
fscanf(pText, "%d", &currQuantity);
to
fscanf(pText, "%d\n", &currQuantity);

Related

Write struct into file in c

I am trying to write struct to file. I have done the part where I defined struct I read text from file and then I saved it in struct now I am on a point where I want to make change in struct: students[i].name and then I want the change to be reflected (write) in file but it has invalid encoding.
file.txt has this structure:
U,Virat Kohli,Virat Kohli,
U,Serena Williams,Virat Kohli,
G,Wayne Gretzky,Virat Kohli,
U,Virat Kohli,Virat Kohli,
U,Serena Williams,Virat Kohli,
G,Wayne Gretzky,Virat Kohli,
Here is my code:
#include <stdio.h>
#include <string.h>
typedef struct
{
// members for the student's type, name, surname
char type;
char name[50];
char surname[50];
} Student;
int main(void)
{
// for comparing strcmp
int result;
// file pointer variable for accessing the file
FILE *file;
// attempt to open file.txt in read mode to read the file contents
file = fopen("file.txt", "r");
// if the file failed to open, exit with an error message and status
if (file == NULL)
{
printf("Error opening file.\n");
return 1;
}
// array of structs for storing the Student data from the file
Student students[100];
// read will be used to ensure each line/record is read correctly
int read = 0;
// records will keep track of the number of Student records read from the file
int records = 0;
// read all records from the file and store them into the students array
while (fscanf(file, " %c , %49[^,], %49[^,],", &students[records].type, students[records].name, students[records].surname) == 3)
{
// if fscanf read 3 values from the file then we've successfully read
records++;
// if there was an error reading from the file exit with an error message
// and status
if (ferror(file))
{
printf("Error reading file.\n");
return 1;
}
}
// close the file as we are done working with it
fclose(file);
// print out the number of records read
printf("\n%d records read.\n\n", records);
// print out each of the records that was read
for (int i = 0; i < records; i++)
printf("%c %s %s\n",
students[i].type,
students[i].name,
students[i].surname);
printf("\n");
// change first record's name to Elena Heis
for (int i = 0; i < 1; i++)
{
if (students[i].name == students[i].name)
{
printf("%s\n",
students[i].name);
strcpy(students[i].name, "Elena Heis");
printf("%s\n",
students[i].name);
}
}
// write changes to file
file = fopen("file.txt", "wb");
if (file != NULL)
{
fwrite(students, sizeof(Student), 1, file);
fclose(file);
}
return 0;
}
After write file has broken encoding like this
It should be
Your code is clean and your format string is almost perfect, yet parsing the csv file (or any file in general) with fscanf() is not recommended as it is very difficult to recover from errors and newlines are mostly indistinguishable from other white space characters. In particular, the \n at the end of the format string will match any possibly empty sequence of white space characters.
Testing ferror() and feof() as you do seems fine but insufficient to ensure reliable parsing: if fscanf() returns a short code, for example because of an empty field, parsing will continue from the middle of the offending line and neither ferror() nor feof() will cause the loop to end.
You should instead read one line at a time with fgets() and use sscanf() to parse the line.
Also note these remarks:
the csv file does not seem to contain name and surname fields but rather the full names of opponents.
this file seems to have trailing , after the third field. If this is expected, the format string ensuring record validity should be changed to "%c,%49[^,],%49[^,\n]%1[,\n]"
you should check that records < 100 to avoid a buffer overflow.
the test if (students[i].name == students[i].name) is useless and always true. No test is needed to change the name of the first student.
you cannot write the text file with fwrite(students, sizeof(Student), 1, file), you should instead use fprintf as for the output to the terminal.
Here is a modified version:
#include <errno.h>
#include <stdio.h>
#include <string.h>
typedef struct
{
// members for the student's type, name, surname
char type;
char name[50];
char surname[50];
} Student;
int main(void)
{
// file pointer variable for accessing the file
FILE *file;
// attempt to open file.txt in read mode to read the file contents
file = fopen("file.txt", "r");
// if the file failed to open, exit with an error message and status
if (file == NULL)
{
fprintf(stderr, "Error opening file %s for reading: %s\n", "file.txt", strerror(errno));
return 1;
}
// array of structs for storing the Student data from the file
Student students[100];
// length of the students array
int nrecords = sizeof(students) / sizeof(*students);
// buffer to read one line at a time
char buffer[256];
// records will keep track of the number of Student records read from the file
int records = 0;
// read all records from the file and store them into the students array
while (records < nrecords && fgets(buffer, sizeof buffer, file))
{
// Read a line/record from the file
// if it was able to read successfully which we expect read will be 3
char newline[3]; // for characters at end of line: `,\n` or `\n`
char extra; // to ensure no more characters are present
// there are 5 conversion specifiers, but sscanf should parse
// exactly 4 fields, including the trailing `,` and the newline
int read = sscanf(buffer,
"%c,%49[^,],%49[^,\n]%2[,\n]%c",
&students[records].type,
students[records].name,
students[records].surname,
newline, &extra);
// if fscanf read 3 values and a newline from the file then we've successfully read
// in another record
if (read == 4) {
records++;
} else {
fprintf(stderr, "invalid record: %s", buffer);
}
}
// if there was an error reading from the file exit with an error message
// and status
if (ferror(file))
{
fprintf(stderr, "Error reading file: %s\n", strerror(errno));
fclose(file);
return 1;
}
// close the file as we are done working with it
fclose(file);
// print out the number of records read
printf("\n%d records read.\n\n", records);
// print out each of the records that was read
for (int i = 0; i < records; i++)
{
printf("%c %s %s\n",
students[i].type,
students[i].name,
students[i].surname);
}
printf("\n");
// change first record's name to Elena Heis
strcpy(students[0].name, "Elena Heis");
printf("%s\n", students[0].name);
// write changes to file
file = fopen("file.txt", "w");
if (file == NULL)
{
fprintf(stderr, "Error opening file %s for writing: %s\n", "file.txt", strerror(errno));
return 1;
}
// print out each of the records that was read
for (int i = 0; i < records; i++)
{
fprintf(file, "%c,%s,%s,\n",
students[i].type,
students[i].name,
students[i].surname);
}
fclose(file);
return 0;
}

Issue in reading specific portion of File

I am trying to extract and print a specific portion of text from a file at a given time.I used ftell() and fseek() to achieve this.
#include <stdio.h> //// include required header files
#include <string.h>
int main()
{
FILE *fp = fopen("myt", "w+");
if (fp == NULL) //// test if file has been opened sucessfully
{
printf("Can't open file\n");
return 1; //// return 1 in case of failure
}
char s[80];
printf("\nEnter a few lines of text:\n");
while (strlen(gets(s)) > 0) //user inputs random data
{ //till enter is pressed
fputs(s, fp);
fputs("\n", fp);
}
long int a = ftell(fp);
fputs("this line is supposed to be printed only ", fp);//line to be
// displayed
fputs("\n", fp);
fputs("this line is also to be printed\n",fp); //line to be
//displayed
fputs("\n",fp);
long int b = ftell(fp);
fputs("this is scrap line",fp);
fputs("\n",fp);
rewind(fp);
fseek(fp, a, SEEK_CUR); //move to the starting position of text to be
//displayed
long int c=b-a; //no of characters to be read
char x[c];
fgets(x, sizeof(x), fp);
printf("%s", x);
fclose(fp);
return 0; //// return 0 in case of success, no one
}
I tried using this approach but the program just prints the first line.The output is as follows:
this line is supposed to be printed only
I want to print both the lines intended to be printed.Please suggest an approach.
I think your intent for the reading portion was
rewind(fp);
fseek(fp, a, SEEK_CUR); //move to the starting position of text to be
//displayed
long int c=b-a; //no of characters to be read
char x[c+1];
int used = 0;
while(ftell(fp) < b)
{
fgets(x+used, sizeof(x)-used, fp);
used = strlen(x);
}
printf("%s", x);
Notes:
I added +1 to the allocation of your buffer x because fgets adds
null termination.
I'm not 100% sure you don't want fflush(fp) between the writes and the reads.

Reading a line from a file at a specific point

so Im writing a code to get scanf a text file and return a format text message log. I'm stuck wondering how to scan strings from file at a certain point and print every string beyond that point E.X When the file scans the line
"332982000 2055552002 2055551001 7 Mr Webb, can I ask you a question?" I scan the first 4 numbers as integers and scan the rest of the written text into an char array starting at "Mr. Webb".
I tried using a for loop with fscanf to scan into an array but it didnt work. I was also thinking I could use malloc just to save space but I dont know what to put in the sizeof argument. Any help would be GREATLY appreciated!
int posix;
int phone1;
int phone2;
int textsize;
int val, val2;
char line[256];
char text[3000];
int len=strlen(line);
int i=0;
printf("\n\nTime %s %s", argv[2], argv[3]);
printf("\n======================================================================================\n\n\n");
FILE* textfile= fopen(argv[1],"r");
fscanf(textfile, "%d %d %d %d %s", &posix, &phone1, &phone2, &textsize, text);
while( fgets(line, sizeof(line), textfile) ) {
val= atoi(argv[2]);
val2=atoi(argv[3]);
if ( (val==phone1) && (val2==phone2) ) {
printf(" %s ", text); //only prints Mr
text=(char*)malloc(sizeof())//tried malloc but not too sure how to use it correctly
for (i=0; i<len; i++) { //tried using for loop here didnt work.
fscanf("%s", text);
}
sortText(phone1, phone2, textsize, text);
//readableTime(posix);
}
else if ( (val2==phone1) && (val==phone2) ) {
printf(" %s ", text);
sortText(phone1, phone2, textsize, text);
//readableTime(posix);
}
fscanf(textfile, "%d %d %d %d %s", &posix, &phone1, &phone2, &textsize, text);
}
fclose(textfile);
return 0;
}
At first, read the entire file into a malloc'd char array. The fseek and ftell give you the file size:
// C99
FILE *fp = fopen("file", "r");
size_t filesize;
fseek(fp, 0, SEEK_END);
filesize = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *filetext = malloc(filesize + 1);
fread(filetext, 1, filesize, fp);
filetext[filesize] = 0;
Then use a buffer for a single line with the size of the entire file so you surely have enough size. sscanf() can be used to read stuff from a string.
int readbytes;
for(int i=0; i < filesize; i+=readbytes) {
char line[filesize];
int posix, phone1, phone2, textsize;
if(EOF == sscanf(
&filetext[i], "%d%d%d%d%[^\n]%n", &posix, &phone1,
&phone2, &textsize, line, &readbytes))
{
break;
}
printf("%d %d %d %d '%s' %d\n", posix, phone1, phone2, textsize, line, readbytes);
}
The format specifier '%[^\n]' means: every character until the next newline character. The format specifier '%n' gives you the number of bytes that have been read with this sscanf call so far, effectively your line size, that you can use to advance the iterator.

How output text when decrypting a hex? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
i am trying to decrypt the hex string: 0440 04b4 04d0 04d0 04dc 03a0 047c 04dc 04e8 04d0 04b0 03a4
It should once decrypted properly read hello world!
however i cannot get it to output the text. instead i get a list of integers. does anyone have any ideas as to how to fix this?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char **argv)
{
char file_name[25];
char c; //Variable to hold current character
int sz; //Length of file therefore size of array
FILE *fp;
FILE *fw;
int flag = 1;
while (flag)
{
printf("enter the name of the file you wish to decrypt\n");
fgets(file_name, sizeof file_name, stdin); //fgets safer than gets, prevents infinite input
printf("Reading: %s.....\n", file_name); //debug print, can remove
strtok(file_name, "\n"); //fgets potentially leaves \n on file name, this removes
fp=fopen(file_name,"rt"); //file is opened
fw = fopen("revertedfile.txt", "w"); //oens write file
if( fp == NULL ) //checks if file empty/doesn't exist
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
//Following code finds length of file by seeking, then resets the file point to the start
fseek(fp, 0L, SEEK_END);
sz = ftell(fp);
printf("Length of file is: %i\n",sz); // Debug print, can delete
fseek(fp, 0L, SEEK_SET);
int data[sz]; //Init array based on file length
int i = 0; //Counter set to 0
while((c=fgetc(fp))!=EOF) //While haven't reached end of file.
{
int ic = (int)c - 200; //minus 200 to the ascii code
//printf("ASCI Code + 100 = %i\n", ic); //debug print
//Could do bit shift before adding to array, I Guess
data[i] = ic; //Add ASCII code to array at i
data[i] = data[i] >> 2; //Bit shift
//Debug print, shows what's happening
int test = data[i];
printf("%i\n", data[i]);
fprintf(fw, "%i\n", data[i]);
//printf("Added %i to the array at point %d\n", test, i);
i++; //Increment pointer for array
}
fclose(fp); //Always close file
fclose(fw); // closes write file
}
return 0;
}
This is the encryption code
printf("enter name of the file you wish to encrypt\n");
fgets(file_name, sizeof file_name, stdin); //fgets safer than gets, prevents infinite input
printf("Reading: %s.....\n", file_name); //debug print, can remove
strtok(file_name, "\n"); //fgets potentially leaves \n on file name, this removes
fp = fopen(file_name,"rt"); //file is opened
fw = fopen("output.txt", "w"); //oens write file
if( fp == NULL ) //checks if file empty/doesn't exist
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
//Following code finds length of file by seeking, then resets the file point to the start
fseek(fp, 0L, SEEK_END);
sz = ftell(fp);
printf("Length of file is: %i\n",sz); // Debug print, can delete
fseek(fp, 0L, SEEK_SET);
int data[sz]; //Init array based on file length
int i = 0; //Counter set to 0
while((c=fgetc(fp))!=EOF) //While haven't reached end of file
{
printf("Current char: %c\n",c); //Debug print
int ic = (int)c + 200; //Add 200 to the ascii code
//printf("ASCI Code + 100 = %i\n", ic); //debug print
//Could do bit shift before adding to array, I Guess
data[i] = ic; //Add ASCII code to array at i
data[i] = data[i] << 2; //Bit shift
//Debug print, shows what's happening
int test = data[i];
printf("%04x ", data[i]);
fprintf(fw, "%04x ", data[i]);
//printf("Added %i to the array at point %d\n", test, i);
i++; //Increment pointer for array
}
fclose(fp); //Always close file
fclose(fw); // closes write file
//Debug
int test2 = data[1];
printf("The new file is named output.txt");
If you want to decrypt it, you need to know how it was encrypted (well, that still might not be enough). If you just need to print the character each ASCII code represents, you just need to tell printf that by using %c instead of %i.

fscanf, structs, and using the struct c programming

/*Project 1
Student records
1. Read the file with the records
2. store them
3. sort them
4. output them
ex. input and output (SORTED by student ID
2040003 AAAA BBBBBBBBB ComputerScience 3.45
2040002 AAA CCC ElectricalEngineering 3.01
2040005 AAAAAAAAAAAAAAAAA BBB ComputerScience 3.60
2040002,AAA,CCC,ElectricalEngineering,3.01
2040003,AAAA,BBBBBBBBB,ComputerScience,3.45
2040005,AAAAAAAAAAAAAAAAA,BBB,ComputerScience,3.60
char* name = malloc(256*sizeof(char));
*/
int main()
{
typedef struct StudentRecords
{
int StudentID; //must be of size 7 between 1000000 and 9999999
char *Firstname; //= MALLOC(256*sizeof(char)); // must be any length and allocate memory dynamically.
char *Lastname; //= MALLOC(256*sizeof(char));
char *Department; //= MALLOC(256*sizeof(char));
float GPA; // must be between 0 and 4
} STUDENTRECORDS;
/*
First job is read the file
*/
//set variables
int i=0;
char filecontent, file_name[100];
FILE *fp;
STUDENTRECORDS StudentRecords[300];
STUDENTRECORDS a[300];
int size =0;
printf("Enter directory of file\n"); // instructs user to enter directory of file
gets(file_name); //prompt use
fp = fopen(file_name,"r"); //opens the file "r" is read mode for fopen()
// here is a check to see if fp is empty and throw an error if so
if (fp == NULL)
{
perror("Could not open file\n");
exit(EXIT_FAILURE);
}
printf("The contents of %s file are :\n", file_name); // just prints the file name (file_name) you are prompted for
// here is where the printing of contents actually occurs
while ((filecontent = fgetc(fp)) != EOF) // I think EOF is end of feed here, not 100%
{
printf("%c",filecontent);
}
//I thought this line was to figure out how many lines are in the text, but it isnt working.
while (!feof(fp))
{
read(StudentRecords, i, fp);
i++;
}
//because the while statement isnt working, Ive elected to setting size to 3 in order to continue coding.
size = i = 3;
printf("Size = %d\n", size);
//I thought this essentially put the files contents into
for (i = 0; i < size; ++i)
fscanf(fp, "%d %s %s %s %f\n", &StudentRecords[i].StudentID, &StudentRecords[i].Firstname, &StudentRecords[i].Lastname, &StudentRecords[i].Department, &StudentRecords[i].GPA);
for (i = 0; i < size; ++i)
printf("%s", StudentRecords[i]);
//printf("%d %s %s %s %f/n", &StudentRecords[i].StudentID, &StudentRecords[i].Firstname, &StudentRecords[i].Lastname, &StudentRecords[i].Department, &StudentRecords[i].GPA);
for (i = 0; i < size; ++i)
fscanf(fp, "%d %s %s %s %f\n", &a[i].StudentID, &a[i].Firstname, &a[i].Lastname, &a[i].Department, &a[i].GPA);
for (i = 0; i < size; ++i)
printf("%s", a[i]);
//printf("%d %s %s %s %f/n", &a[i].StudentID, &a[i].Firstname, &a[i].Lastname, &a[i].Department, &a[i].GPA);
// fclose() must follow an fopen()
fclose(fp);
//printf("%g", &StudentRecords);
// return code
return 0;
}
How do I add information into a struct and print it or use it? This is what
i have so far. I've tried many different things and to no avail. I think the problem is with my initializing my struct for use. I can't get it right. I've tried searching for a solution, but each one is different and don't explain much.
Thanks for any suggestions.
Please find example code for reading content from file and storing it in structure also for this example have only take 5 student data entry(you can change as you wish) And on which criteria you want to do sorting? So i leave sorting on you.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_ENTRY 5
typedef struct StudentRecords
{
int StudentID; //must be of size 7 between 1000000 and 9999999
char *Firstname; //= MALLOC(256*sizeof(char)); // must be any length and allocate memory dynamically.
char *Lastname; //= MALLOC(256*sizeof(char));
char *Department; //= MALLOC(256*sizeof(char));
float GPA; // must be between 0 and 4
} STUDENTRECORDS;
int main()
{
/*
First job is read the file
*/
//set variables
int i=0;
char filecontent, file_name[100];
FILE *fp;
STUDENTRECORDS StudentRecords[MAX_ENTRY];
for(i=0;i<MAX_ENTRY;i++)
{
StudentRecords[i].Firstname = malloc(sizeof(char)*256);
StudentRecords[i].Lastname = malloc(sizeof(char)*256);
StudentRecords[i].Department = malloc(sizeof(char)*256);
}
printf("Enter directory of file\n"); // instructs user to enter directory of file
gets(file_name); //prompt use
fp = fopen(file_name,"r"); //opens the file "r" is read mode for fopen()
// here is a check to see if fp is empty and throw an error if so
if (fp == NULL)
{
perror("Could not open file\n");
//exit(EXIT_FAILURE);
}
i=0;
while(EOF!=fscanf(fp, "%d %s %s %s %f\n", &StudentRecords[i].StudentID, StudentRecords[i].Firstname, StudentRecords[i].Lastname, StudentRecords[i].Department, &StudentRecords[i].GPA))
{
printf("%d %s %s %s %f\n", StudentRecords[i].StudentID, StudentRecords[i].Firstname, StudentRecords[i].Lastname, StudentRecords[i].Department, StudentRecords[i].GPA);
i++;
}
// fclose() must follow an fopen()
fclose(fp);
return 0;
}
Note: never forgot to free string which allocated by malloc after it's use.
A few comments, and some suggestions:
Was it your lecturer who said to use a linked-list? If so.. you really should do that otherwise you'll lose marks for failing to meet the spec.
EOF is 'End Of File'. feof() tells you if the stream pointer passed to it has hit EOF already.
Your while loop to print the contents is inefficient. Rather than reading every. single. character. in. the. file., you should read the entire file (or at least, large chunks thereof, let's not assume infinite memory), fclose() the stream and then operate on the read-in file.
Also, this sort of exercise lends itself very well to fixed-size record
Omitting error handling, variable declarations, structures and
using some pseudocode:
stat("/path/to/file", &statbuf)
inputfd = fopen("/path/to/file", r);
/* assuming that we only have a small file... */
contents = calloc(statbuf.st_size * sizeof(char));
/* read it all in, in one big chunk */
fread(contents, statbuf.st_size, 1, inputfd);
fclose(inputfd);
/* Now you can operate on it however you like */
bytesleft = statbuf.st_size;
/*
* this might need to go at the top of your block, depends on if you
* have enabled C99
*/
char eachline[MAXLINELENGTH];
int n = 0;
while (bytesleft > 0) {
add_new_list_element(mylist);
bzero(eachline, MAXLINELENTH);
memccpy(&eachline, contents[n], '\n', MAXLINELENGTH);
bytesleft -= sizeof(eachline);
nread = sscanf(start, "USE YOUR FORMAT STRING HERE", [variable list]);
if (nread < 0)
/* handle EOF, remember to make use of errno */
}
call_my_sort_function(mylist);
for (; thiselement != NULL; thiselement = thiselement->next)
print_salient_field_values(thiselement);

Resources