This program will read data in the form of:
Number Name
In each line of a text file, then it will write it to a binary file and print the resulting binary file.
I am getting a warning in line 73, but I don't think it's an issue as null is converted into 0, right?
while(((fread((char*)&student, 1, sizeof(student), binary_file)) != NULL))
I'm talking about this line above
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 50
void create_binary_file(const char *dest, const char *src);
void print_binary_file(const char *dest);
int main(void){
const char ascii[MAX_SIZE] = "text.txt";
char binary[MAX_SIZE];
puts("Enter the name of the binary file");
fgets(binary, sizeof(binary), stdin);
binary[strlen(binary)-1] = '\0';
create_binary_file(binary, ascii);
print_binary_file(binary);
return 0;
}
void create_binary_file(const char *dest, const char *src){
struct student_tem{
int ID;
char name[MAX_SIZE];
};
struct student_tem student;
FILE *text_file;
FILE *binary_file;
if((text_file = fopen(src, "r")) == NULL){
perror(src);
exit(EXIT_FAILURE);
}
if((binary_file = fopen(dest, "wb")) == NULL){
perror(dest);
exit(EXIT_FAILURE);
}
while(!feof(text_file)){
if(1 != fscanf(text_file, "%i", &student.ID)){
fprintf(stderr, "Error reading student number");
exit(EXIT_FAILURE);
}
if(1 != fscanf(text_file, "%s", student.name)){
fprintf(stderr, "Error reading student name");
exit(EXIT_FAILURE);
}
fwrite(&student, 1, sizeof(student), binary_file);
}
fclose(text_file);
fclose(binary_file);
}
void print_binary_file(const char *dest){
struct student_tem{
int ID;
char name[MAX_SIZE];
};
struct student_tem student;
FILE *binary_file;
if((binary_file = fopen(dest, "rb")) == NULL){
perror(dest);
exit(EXIT_FAILURE);
}
while(((fread((char*)&student, 1, sizeof(student), binary_file)) != NULL)){
printf("%i %s\n", student.ID, student.name);
}
}