Hello,
I am working with file I/O at the moment. I am attempting to read in numbers from an ascii file and then write them to a binary file. My program is opening the ascii file correctly, and it is opening and writing data to the new file also.
The issue is when I enter ls -l from the command prompt the "ascii" and "binary" files are the same size. I would expect the binary file to be significantly smaller as I would expect the ascii file to have two bytes for say 66 and the binary to use one byte to represent it. I've been digging through the forums and google and am not quite sure why I am not getting results that I would expect. I have also attached the ascii file, I tried uploading the binary file(tried adding .bin.txt to the file, no extension, only .txt) but it won't allow me to attach it.
Thank you for any discussion/enlightenment.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void write_binary(FILE *ascii_pointer, FILE *binary_pointer);
void close_files(FILE *ascii_pointer, FILE *binary_pointer);
int main(){
FILE *input_file; /* Pointer for the ascii input file */
FILE *output_file; /* Pointer for the binary output file */
/*open_files(input_file,output_file);*/
input_file = fopen("ASCIItest.txt", "r");
output_file = fopen("BINARYtest.bin","wb");
/* pass pointers to read in ascii and write to binary file */
write_binary(input_file,output_file);
/* pass pointers to files to be closed */
close_files(input_file, output_file);
return(0);
}
/*
FUCTION WRITE BINARY
About: This function reads in characters from an ascii file
and writes them to a binary file.
This Function accepts two pointers as its arguments
-- ascii_pointer == pointer to an ascii file to be
read from.
-- binary_pointer == pointer to a binary file to be
written to.
*/
void write_binary(FILE *ascii_pointer, FILE *binary_pointer){
char ch; /* character variable for reading in numbers from the ascii file */
/* get a character from the ascii file */
ch = fgetc(ascii_pointer);
/* loop until end of file is reached */
while(ch != EOF){
/* write the character to the file using fwrite */
fwrite(&ch, sizeof(ch),1,binary_pointer);
/* get a new character */
ch = fgetc(ascii_pointer);
}
}
/* function to close pointers */
void close_files(FILE *ascii_pointer, FILE *binary_pointer){
fclose(ascii_pointer);
fclose(binary_pointer);
}
ASCIItest.txt
******EDIT*****
Also I tried opening both files in gedit as well as vim and both were viewable in what seemed to be the original ascii characters, I went over to windows and was able to view both with notepad. I thought I would get something odd with the binary file in windows but I did not. I don't know if this will be helpful but thought I would include it. Thanks.