I am creating a text file based on a binary file , reading the records from the binary file and writing them in the text file. The first subprogram is the creation of the binary file and the second for creating the text file.
#include<stdio.h>
typedef struct {
char CNP[14];
char nume[30];
int an;
int grupa;
int nrDisc;
int note[20];
}STUDENT;
void creare(char*nume) {
FILE*f;
STUDENT s;
fopen_s(&f, nume, "wb");
if (!f)
printf("Eroare");
else {
printf("CNP:");
gets(s.CNP);
while (!feof(stdin)){
printf("Nume:");
gets(s.nume);
printf("An:");
scanf_s("%d", &s.an);
printf("Grupa:");
scanf_s("%d", &s.grupa);
printf("Nr. discipline:");
scanf_s("%d", &s.nrDisc);
for (int i = 0; i < s.nrDisc; i++)
{
printf("Nota[%d] este:", i);
scanf_s("%d", &s.note[i]);
}
fwrite(&s, sizeof(s), 1, f);
getchar();
printf("CNP:");
gets(s.CNP);
}
fclose(f);
}
}
void raport(char*nume_binar, char*nume_text) {
FILE*f;
fopen_s(&f, nume_binar, "rb");
if (!f)
printf("Eroare");
else {
FILE*g;
STUDENT s;
fopen_s(&g, nume_text, "w");
while (fread(&s, sizeof(s), 1, f)==sizeof(s));
{
fprintf(g,"%s %s %d %d %d\n ", s.CNP, s.nume, s.an, s.grupa, s.nrDisc);
for (int i = 0; i < s.nrDisc; i++)
{
fprintf(g, "Nota %d este:", i);
fprintf(g, "%d\n", s.note[i]);
}
}
fclose(g);
}
fclose(f);
}
void main() {
char nume_fisier[] = "Student.dat";
char nume_fisier_txt[] = "Raport.txt";
//creare(nume_fisier);
raport(nume_fisier, nume_fisier_txt);
}
For example , I am writing 2 records in the binary file, but only the last record appears in the text file.
while (fread(&s, sizeof(s), 1, f)==sizeof(s));
You have an extra semicolon ';' here. It leads to while loop running continuously until it reaches end of file that is structure s contains last structure.
It means that
{
fprintf(g,"%s %s %d %d %d\n ", s.CNP, s.nume, s.an, s.grupa, s.nrDisc);
for (int i = 0; i < s.nrDisc; i++)
{
fprintf(g, "Nota %d este:", i);
fprintf(g, "%d\n", s.note[i]);
}
}
this block writing to text file runs only once and for last structure of binary file.
Also note that fread returns number of elements read not size of elements read so that statement should be while(fread(&s, sizeof(s), 1, f) == 1) {...}
Related
I need to solve a problem. I need to create two functions which scan user's input information and put in into structure array and then put all array to BIN file (with function fwrite()) and other function - read from BIN file with function fread(). You can see my code below. Problem is that I can write to file, but when I read I get filler array element and other element which are empty. How to get only filled struct array element?
#include <stdio.h>
#include <stdlib.h>
#include <mem.h>
typedef struct
{
char Lesson[50];
char TeachersName[50];
char TeachersLastName[50];
int Credits;
int NumberOfStudents;
} School;
void ToFile (char *fileName);
void FromFile (char *FileName);
int main()
{
char *fileName[]={"student.bin"};
ToFile (*fileName);
FromFile (*fileName);
return 0;
}
void ToFile (char *fileName)
{
int n, chars;
FILE *fp;
fp = fopen(fileName, "wb");
School Info[20];
if(fp == NULL)
{
printf("Error opening file\n");
exit(1);
}
printf("Testing fwrite() function: \n\n");
printf("Enter the number of records you want to enter: ");
scanf("%d", &n);
for(int i = 0;i<n;i++)
{
printf("\nEnter details of employee %d \n", i + 1);
fflush(stdin);
printf("Lesson: ");
gets(Info[i].Lesson);
printf("Teachers name: ");
gets(Info[i].TeachersName);
printf("Teachers last name: ");
gets(Info[i].TeachersLastName);
printf("Credits: ");
scanf("%d", &Info[i].Credits);
printf("Number of studens: ");
scanf("%d", &Info[i].NumberOfStudents);
chars = fwrite(&Info[i], sizeof(Info), 1, fp);
printf("Number of items written to the file: %d\n", chars);
}
fclose(fp);
}
void FromFile (char *FileName)
{
School Info[20]= { { "", "","",0,0 } };;
FILE * fpp;
fpp = fopen(FileName, "rb");
fread(&Info, sizeof(Info), 1, fpp);
/*
for(int j=0; j<20; ++j) {
printf("\nLesson: %s", Info[j].Lesson);
printf("\nTeachers name: %s", Info[j].TeachersName);
printf("\nTeachers last name: %s", Info[j].TeachersLastName);
printf("\nCredits: %d", Info[j].Credits);
printf("\nNumber of students: %d", Info[j].NumberOfStudents);
printf("\n");
}*/
int j=0;
while (fread(&Info, sizeof(Info), 1, fpp))
{
printf("\nLesson: %s", Info[j].Lesson);
printf("\nTeachers name: %s", Info[j].TeachersName);
printf("\nTeachers last name: %s", Info[j].TeachersLastName);
printf("\nCredits: %d", Info[j].Credits);
printf("\nNumber of students: %d", Info[j].NumberOfStudents);
printf("\n");
j++;
}
fclose(fpp);
}
Im trying to read a text file into an array of structs, but when trying to print the array, the struct is empty. The printing function works fine and I think the problem is in getRawData.
struct student
{
char ID[MAXID + 1];
char f_name[FIRST_NAME_LENGTH + 1];
char s_name[LAST_NAME_LENGTH + 1];
int points[MAXROUNDS];
};
//main//
case 'W':
if(save(array, len) == 0);
{
printf("Data saved.\n");
}
break;
case 'O':
if(getRawData(array, len));
{
printf("File read.\n");
}
break;
int save(struct student *h, int num_students)
{
char name[20];
printf("Enter file name: " );
scanf("%s", name); // Read in filename
FILE *output = fopen(name, "w"); // open the file to write
if (!output) {
return -1; // error
}
for (int i = 0; i < num_students; ++i)
{
fprintf(output, "%s %s %s \n", h[i].f_name, h[i].s_name, h[i].ID);
for(int j = 0; j < MAXROUNDS; j++)
{
fprintf(output, "%d\n", h[i].points[j]);
}
printf("Information of student %s %s (%s) written into file %s\n", h[i].s_name, h[i].f_name, h[i].ID, name);
}
fclose(output); // close
return 0;
}
int getRawData(struct student *records)
{
int i;
int nmemb; // amount of structs
char name[20];
printf("Name of the file to be opened: \n");
scanf("%s", name);
FILE *outtput = fopen(name, "r");
int ch=0;
int lines=0;
if (outtput == NULL);
return 0;
lines++;
while(!feof(outtput))
{
ch = fgetc(outtput);
if(ch == '\n')
{
lines++;
}
}
nmemb = lines / 7;
for(i = 0; i < nmemb; i++) {
fscanf(outtput, "%s %s %s", records[i].f_name, records[i].s_name, records[i].ID);
for(int j = 0; j < MAXROUNDS; j++)
{
fscanf(outtput, "%d\n", &records[i].points[j]);
}
}
printf("%d", lines);
return i;
}
So my goal is to get the data from the file and write it over whatever there is stored in the struct array. I would appreciate some help as I have been working on this for way too long.
Look at this code in getRawData(), first you are reading file to identify total number of lines:
while(!feof(outtput))
{
ch = fgetc(outtput);
if(ch == '\n')
.....
.....
due to this the file stream pointer pointing to EOF and after this, in the for loop, you are doing:
for(i = 0; i < nmemb; i++) {
fscanf(outtput, "%s %s %s", records[i].f_name, records[i].s_name, records[i].ID);
.....
.....
Here, the fscanf() must be returning the EOF because there is nothing remain to read from stream file. You should check the return value of fscanf() while reading file.
You should reset the pointer to start of file before reading it again. You can use either rewind(ptr) or fseek(fptr, 0, SEEK_SET). Below is a sample program to show you what is happening in your code and how the solution works:
#include <stdio.h>
int main (void) {
int ch;
int lines = 0;
char str[100];
FILE *fptr = fopen ("file.txt", "r");
if (fptr == NULL) {
fprintf (stderr, "Failed to open file");
return -1;
}
while (!feof(fptr)) {
ch = fgetc (fptr);
if(ch == '\n') {
lines++;
}
}
printf ("Number of lines in file: %d\n", lines);
printf ("ch : %d\n", ch);
printf ("Now try to read file using fscanf()\n");
ch = fscanf (fptr, "%s", str);
printf ("fscanf() return value, ch : %d\n", ch);
printf ("Resetting the file pointer to the start of file\n");
rewind (fptr); // This will reset the pointer to the start of file
printf ("Reading file..\n");
while ((ch = fscanf (fptr, "%s", str)) == 1) {
printf ("%s", str);
}
printf ("\nch : %d\n", ch);
fclose (fptr);
return 0;
}
The content of file reading in the above program:
Hello Vilho..
How are you!
Output:
Number of lines in file: 2
ch : -1
Now try to read file using fscanf()
fscanf() return value, ch : -1
Resetting the file pointer to the start of file
Reading file..
HelloVilho..Howareyou!
ch : -1
Here you can see, the first ch : -1 indicate that the file pointer is at EOF and if you try to read you will get EOF because there is nothing left to read. After resetting file pointer, you can see fscanf() is able to read file.
You should not use while (!feof(file)). Check this.
I have coded a formula to read the txt file, store it in array(1D) and then reading the array to calculate the moving average(2D). Program ask the user to input two values (k1 & k2) and calculate the moving average for every value from k1 to k2 (basically to find out the best value)
Following is the code
#include<stdlib.h>
#define MAX_FILE_NAME 100
#define MAXCHAR 1000
int main()
{
FILE *fp;
int count = 0,k1=0,k2=0,k=0; // Line counter (result)
int buy[k2][count],sell[k2][count];
char filename[MAX_FILE_NAME];
char c; // To store a character read from file
// Get file name from user. The file should be
// either in current folder or complete path should be provided
printf("Enter file name or full path: ");
scanf("%s", filename);
printf("Enter the minimum rolling period for calculation : \n");
scanf("%d", &k1);
printf("Enter the maximum rolling period for calculation : \n");
scanf("%d", &k2);
// Open the file
fp = fopen(filename, "r");
// Check if file exists
if (fp == NULL)
{
printf("Could not open file %s", filename);
return 0;
}
// Extract characters from file and store in character c
for (c = getc(fp); c != EOF; c = getc(fp))
if (c == '\n') // Increment count if this character is newline
count = count + 1;
// Close the file
fclose(fp);
//printf("The file %s has %d lines\n", filename, count);
FILE *myFile;
myFile = fopen(filename, "r");
//read file into array
float numberArray[count];
int i;
if (myFile == NULL){
printf("Error Reading File\n");
exit (0);
}
for (i = 0; i < count; i++){
fscanf(myFile, "%f,", &numberArray[i]);
}
fclose(myFile);
for (k=k1;k<=k2;k++)
{
float n;
float data[count],mag[k2][count];
double avg,sum;
for (i=0;i<k-1;i++)
{
mag[k][i-1]=0;
sum=sum+numberArray[i];
}
for(i=k-1;i<=count;i++)
{
mag[k][i-1]=avg;
sum=sum+numberArray[i]-numberArray[i-k];
avg = sum/k;
}
// for(i=0;i<=count;i++)
// {
// printf("MA[%d][%d] = %0.2lf ",k,i,mag[k][i]);
// if (i%3==0)
// printf("\n");
// }
}
for(k=k1;k<=k2;k++)
{
for(i=0;i<=count;i++)
printf("MA[%d][%d] = %0.2lf ",k,i,mag[k][i]);
}
}
}
Now when I am trying to print mag[k][i] values outside the for loop, it is showing error 'mag' undeclared. But when I am putting the print command inside the loop (comment out portion in the code), it works fine.
UPDATED CODE AFTER FOLLOWING COMMENTS (STILL NOT WORKING THOUGH)
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
#define MAX_FILE_NAME 100
#define MAXCHAR 1000
int main()
{
FILE *fp;
int count,k1,k2,k; // Line counter (result)
char filename[MAX_FILE_NAME];
char c; // To store a character read from file
// Get file name from user. The file should be
// either in current folder or complete path should be provided
printf("Enter file name or full path: ");
scanf("%s", filename);
printf("Enter the minimum rolling period for calculation : \n");
scanf("%d", &k1);
printf("Enter the maximum rolling period for calculation : \n");
scanf("%d", &k2);
// Open the file
fp = fopen(filename, "r");
// Check if file exists
if (fp == NULL)
{
printf("Could not open file %s", filename);
return 0;
}
// Extract characters from file and store in character c
for (c = getc(fp); c != EOF; c = getc(fp))
if (c == '\n') // Increment count if this character is newline
count = count + 1;
// Close the file
fclose(fp);
//printf("The file %s has %d lines\n", filename, count);
/****************
File opening and reading section
*****************************************************/
FILE *myFile;
myFile = fopen(filename, "r");
//read file into array
float numberArray[count];
int i;
if (myFile == NULL){
printf("Error Reading File\n");
exit (0);
}
for (i = 0; i < count; i++){
fscanf(myFile, "%f,", &numberArray[i] );
}
fclose(myFile);
/***********************************************
Calculation of Moving Average and storing it in array
******************************************/
int buy[k2][count],sell[k2][count];
float mag[k2][count];
for (k=k1;k<=k2;k++)
{
float data[count];
double avg,sum;
for (i=1;i<k;i++)
{
mag[k][i-1]=0;
sum=sum+numberArray[i];
}
for (i=k-1;i<=count;i++)
{
mag[k][i-1]=avg;
sum=sum+numberArray[i]-numberArray[i-k];
avg = sum/k;
}
// for(i=0;i<=count;i++)
// {
// printf("MA[%d][%d] = %0.2lf ",k,i,mag[k][i]);
// if (i%3==0)
// printf("\n");
// }
}
for (k=k1;k<=k2;k++)
{
for (i=0;i<=count;i++)
{
printf("MA[%d][%d] = %0.2lf ",k,i,mag[k][i]);
}
}
}
The problem boils down to this: the scope of mag is limited to the inside of the for loop:
for (k = k1; k <= k2; k++)
{
...
int mag[k2][count];
...
}
// mag is out of scope here
// therefore following line won't compile:
printf("%d", mag[0][0]);
You need to declare mag outside the for loop for example like this:
int mag[k2][count];
for (k = k1; k <= k2; k++)
{
...
}
printf("%d", mag[0][0]);
...
Beware: there are other problems within your code, mentioned in the comments.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SLENG 50 //just a random value
typedef struct Song
{
char *name;
char *nameSong;
char *timeSong;
int date;
} Song;
void saveToFile(Song *x, int *songCount) //Saves info to the binary file
{
FILE *f = fopen("array.txt", "w");
if (f == NULL)
{
printf("Error\n");
}
fwrite(songCount, sizeof(int), 1, f);
fwrite(x, sizeof(struct Song), (*songCount), f);
fclose(f);
}
void readSong(Song *x, int *songCount) //Reads info fromt he file and writes it
{
FILE *fr = fopen("array.txt", "r");
if (fr == NULL)
{
printf("Error\n");
}
printf("Songs:\n");
fread(songCount, sizeof(int), 1, fr);
fread(x, sizeof(struct Song), (*songCount), fr);
for(int i=0; i < (*songCount); i++)
{
printf("%d. %s %s %s %d\n", (i+1), x[i].name, x[i].nameSong, x[i].timeSong, x[i].date);
}
fclose(fr);
}
void insertSong(Song *x, int Count) //Inserts new song into the array.
{
printf("\nInsert name of the band:\n");
x[Count].name=malloc(SLENG * sizeof(char));
scanf("%s", x[Count].name);
printf("Insert name of the song:\n");
x[Count].nameSong=malloc(SLENG * sizeof(char));
scanf("%s", x[Count].nameSong);
printf("Insert length of the song:\n");
x[Count].timeSong=malloc(SLENG * sizeof(char));
scanf("%s", x[Count].timeSong);
printf("Insert then song was created:\n");
scanf("%d", &(x[Count].date));
printf("\n");
}
main()
{
int songCount, menuOption;
Song *x=malloc(SLENG*sizeof(char)+SLENG*sizeof(char)+SLENG*sizeof(char)+sizeof(int));
printf("1. insert song\n 2. load from file\n ");
scanf("%d", &menuOption);
switch(menuOption)
{
case(1) :
printf("Insert how many songs do you want to input?\n");
scanf("%d", &songCount);
for(int i=0; i<songCount; i++)
{
insertSong(x, i);
}
saveToFile(x, &songCount);
break;
case(2) :
readSong(x, &songCount);
break;
}
}
I have an assingment to write a programm which would input some data into file and could read that data from that file, the problem is probably with fwrite or fread, couse it seems to crash everytime I try to load the and write the data from file. Any ideas why is it not working properly? And can I even do it like this as it is dynamic struct array. Thanks in advance.
In order to save the structure to a file, it must only contain scalar values, not pointers into memory objects. Modify your structure to use arrays instead of pointers:
typedef struct Song {
char name[SLENG];
char nameSong[SLENG];
char timeSong[SLENG];
int date;
} Song;
And modify the code accordingly, but note that:
saving and reading the structures to and from a file requires opening it in binary mode "wb" and "rb".
it is very misleading to name a binary file array.txt.
you do not need to pass the address of the count when writing to the file, but you need to pass the address of the array pointer when reading as you do not know yet how much memory to allocate.
Here is the modified code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SLENG 50 // this value is used in the file format
typedef struct Song {
char name[SLENG];
char nameSong[SLENG];
char timeSong[SLENG];
int date;
} Song;
int saveToFile(Song *x, int songCount) { //Saves info to the binary file
FILE *f = fopen("array.bin", "wb");
if (f == NULL) {
printf("Error\n");
return -1;
}
fwrite(songCount, sizeof(int), 1, f);
int written = fwrite(x, sizeof(struct Song), songCount, f);
fclose(f);
return written;
}
int readSong(Song **x, int *songCount) { //Reads info from the file and writes it
int count = 0;
FILE *fr = fopen("array.bin", "rb");
if (fr == NULL) {
printf("Error\n");
return -1;
}
printf("Songs:\n");
fread(&count, sizeof(int), 1, fr);
*x = calloc(count, sizeof(Song));
if (*x == NULL) {
printf("Cannot allocate %d bytes of memory\n", count);
fclose(fr);
return -1;
}
int found = fread(*x, sizeof(struct Song), count, fr);
for (int i = 0; i < found; i++) {
printf("%d. %s %s %s %d\n", i + 1,
(*x)[i].name, (*x)[i].nameSong, (*x)[i].timeSong, (*x)[i].date);
}
fclose(fr);
return *songCount = found;
}
void insertSong(Song *x, int Count) { //Inserts new song into the array.
printf("\nInsert name of the band:\n");
scanf("%49s", x[Count].name);
printf("Insert name of the song:\n");
scanf("%49s", x[Count].nameSong);
printf("Insert length of the song:\n");
scanf("%49s", x[Count].timeSong);
printf("Insert then song was created:\n");
scanf("%d", &(x[Count].date));
printf("\n");
}
int main(void) {
int songCount, menuOption;
Song *x = NULL;
printf("1. insert song\n 2. load from file\n ");
scanf("%d", &menuOption);
switch (menuOption) {
case 1:
printf("Insert how many songs do you want to input?\n");
if (scanf("%d", &songCount) == 1) {
x = calloc(songCount, sizeof(Song));
for (int i = 0; i < songCount; i++) {
insertSong(x, i);
}
saveToFile(x, songCount);
}
break;
case 2:
readSong(&x, &songCount);
break;
}
free(x);
x = NULL;
return 0;
}
When running this code with an input .txt file containing somewhere between 200-300 integers (separated by spaces) i get an error right before the for loop with the fprintf statement.
I am not sure if qsort is causing this error or why it occurs but any insight would be appreciated.
(this file is run by adding the name of the input file and the output file in the command line ex: ./program input.txt output.txt
My code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int cmpfunc (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int main(int argc, char *argv[]){
if(argc != 3){
printf("\nInvalid input\nPlease provide the input and output text file names as %s name1 name2\n", argv[0]);
}else{
printf("\nPart A: \n");
printf("..............................................................................................................\n\n");
char *fn1 = argv[1]; //variables
char *fn2 = argv[2];
int temp = 0;
int counter = 0;
int index = 0;
int index2 = 0;
int sort = 0;
FILE *fp1 = fopen(fn1, "r"); //read file
FILE *fp2 = fopen(fn2, "w"); //write file
if(fp1 == NULL){ //test if fp1 was opened
printf("There was an error opening the input file");
}
char data[10]; //ints can only hold 10 digits
int *integerArr;
int *tempPointer;
integerArr = malloc(10*sizeof(int));
int sizeOfArrs = 10;
printf("Reading in the textfile: ");
while(fscanf(fp1,"%s",data) != EOF){ //reads in the file breaking on each whitespace and ends at the EOF pointer
temp = strlen(data);
if(temp <=10){
temp = atoi(data);
integerArr[counter] = temp;
printf(".");
counter++;
if(counter == sizeOfArrs -1){
temp = sizeOfArrs * 2;
tempPointer = realloc(integerArr, temp);
if(tempPointer != NULL){
integerArr = tempPointer;
}
}
}else printf("\ninteger had too many digits\n");
}
printf(" Done\n%d Numbers were found\n", counter);
printf("The integers found in the %s file: \n", argv[1]);
index = 0; //reset index to 0;
for(index;index<counter;index++){ //prints the unsorted contents of the file
printf("%d ", integerArr[index]);
}
printf("\n\nPart B\n");
printf("..............................................................................................................\n\n");
printf("The integers found in the %s file after sorting: \n", argv[1]);
qsort(integerArr, counter, sizeof(int), cmpfunc); //best function ever (sorts the array using the cmpfunc to tell if an integer is greater than less than or equal to the next one)
index = 0; //resets the index
for(index; index <counter; index++){ //prints the sorted contents of the file
printf("%d ", integerArr[index]);
fprintf(fp2,"%d ",integerArr[index]); //writes the sorted integers to the new file
}
if(fp2 == NULL){ //tests if the write worked
printf("There was an error writing the outputfile");
}
printf("\n");
close(fp1,fp2); //closes both files
}
return 0;
}
Your fscanf loop is broken. You weren't actually realloc'ing with a larger size. Here's the corrected program [sorry for the pedantic style reedit but you hit one of my nits: long sidebar comments]
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int
cmpfunc(const void *a, const void *b)
{
return (*(int *) a - *(int *) b);
}
int
main(int argc, char *argv[])
{
if (argc != 3) {
printf("\nInvalid input\nPlease provide the input and output text file names as %s name1 name2\n", argv[0]);
return 1;
}
printf("\nPart A: \n");
printf("..............................................................................................................\n\n");
char *fn1 = argv[1]; // variables
char *fn2 = argv[2];
int temp = 0;
int counter = 0;
int index = 0;
int index2 = 0;
int sort = 0;
FILE *fp1 = fopen(fn1, "r");
FILE *fp2 = fopen(fn2, "w");
// test if fp1 was opened
if (fp1 == NULL) {
printf("There was an error opening the input file");
return 1;
}
// ints can only hold 10 digits
char data[10];
int *integerArr;
int *tempPointer;
int sizeOfArrs = 10;
integerArr = malloc(sizeOfArrs * sizeof(int));
printf("Reading in the textfile: ");
// reads in the file breaking on each whitespace and ends at the EOF
// pointer
while (fscanf(fp1, "%s", data) != EOF) {
temp = strlen(data);
if (temp > 10) {
printf("\ninteger had too many digits\n");
continue;
}
temp = atoi(data);
integerArr[counter] = temp;
printf(".");
counter++;
if (counter == sizeOfArrs - 1) {
sizeOfArrs += 600;
integerArr = realloc(integerArr, sizeOfArrs * sizeof(int));
}
}
// trim array to actual size needed
sizeOfArrs = counter;
integerArr = realloc(integerArr, sizeOfArrs * sizeof(int));
printf(" Done\n%d Numbers were found\n", counter);
printf("The integers found in the %s file: \n", argv[1]);
// prints the unsorted contents of the file
for (index = 0; index < counter; index++) {
printf("%d ", integerArr[index]);
}
printf("\n\nPart B\n");
printf("..............................................................................................................\n\n");
printf("The integers found in the %s file after sorting: \n", argv[1]);
// best function ever (sorts the array using the cmpfunc to tell if an
// integer is greater than less than or equal to the next one)
qsort(integerArr, counter, sizeof(int), cmpfunc);
// prints the sorted contents of the file
for (index = 0; index < counter; index++) {
printf("%d ", integerArr[index]);
// writes the sorted integers to the new file
fprintf(fp2, "%d ", integerArr[index]);
}
// tests if the write worked
if (fp2 == NULL) {
printf("There was an error writing the outputfile");
}
printf("\n");
// closes both files
fclose(fp1);
fclose(fp2);
return 0;
}
Also, note the fclose's at the bottom. There are a few minor bugs left for you to find.