convert Ascii code file into binary file - c

I have a problem of converting ASCII code file into binary file. The code is able to read file and print data into other file as ASII code ( using fprintf); however, when I try to convert from ASII code to binary file ( using fwrite), and then use (fread) the file again. It doesn't generate the right answer. My doubt is the fwrite function doesn't work probably. Could you please advise on how to fix this problem? Thank you very much.
============================================
Code to convert from ASCII to binary file
===========================================
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
typedef struct _FileData
{
int a;
double b;
char dataStr[56];
}FileData;
int main()
{
// open read file
FILE * infile=fopen("output.txt", "r");
if(infile==NULL)
{
printf("Error opening file");
exit(1);
}
// open write file
FILE * outfile = fopen("out_file.txt","wb");
if( outfile==NULL)
{
printf("Error writting on file");
exit(1);
}
FileData input; // pointer for read file
FileData output; // pointer for write file
while( fscanf(infile,"%d %lf %[^\n]s",&input.a,&input.b,&input.dataStr)==3)
{
/*printf("%d\n",input.a);
printf("%.3lf\n",input.b);
printf("%s\n",input.dataStr);*/
//fprintf(outfile,"%d\n %.3lf\n %s\n",input.a,input.b,input.dataStr);
fwrite(&output,sizeof(FileData),1,outfile);
}
fclose(infile);
fclose(outfile);
return 0;
}
==============================================================
Code to convert from binary file to ASCII code file
=============================================================
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
typedef struct FileData
{
int a;
double b;
char dataStr[56];
}FileData;
int main()
{
FILE * infile=fopen("out_file.txt", "rb");
if(infile==NULL)
{
printf("Error opening file");
}
FileData input;
while(fread(&input,sizeof(struct FileData),sizeof(struct FileData),infile))
{
printf("%d\n",input.a);
printf("%.3f\n",input.b);
printf("%s\n",input.dataStr);
}
return 0;
}
===========================================================
Data
==========================================================
47
34.278
This is a line of text
48
23.678
This a very very long line

fread(&input,sizeof(struct FileData),sizeof(struct FileData),infile)
should be changed to
fread(&input,sizeof(struct FileData),1,infile)
You want to write 1 struct of size sizeof(struct FileData)
Also check the answer of mash5 where he suggests writing variable input instead of output while writing with fwrite.

In your ASCII conversion code, the input file is read into one variable input
fscanf(infile,"%d %lf %[^\n]s",&input.a,&input.b,&input.dataStr)
but a different, uninitialized, variable output is being written to the output file:
fwrite(&output,sizeof(FileData),1,outfile);
Perhaps you should write
fwrite(&input,sizeof(input),1,outfile);
instead?

Related

How do I read data from a file from each line and store it into a structure array

Below is my code, I have been working on this part for some structure am create a C socket server that can process data for clients, but I got a problem in file handling. I wanted to pick data from a file and store it into a structure at specific portions and then I erase the file according to data I have picked.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "struct.h"
struct student {
char command[10];
char value[50];
char user[50];
};
int main() {
int size, i;
struct student s1[256];
FILE *file = fopen("file.txt", "r");
if (file == NULL) {
printf("Error in reading student data");
return 1;
}
size = 0;
while(fscanf(file,"%s,%s,%s",
s1[size].command,
s1[size].value,
s1[size].user) != EOF) {
printf("%s%s%s\n",s1[size].command,s1[size].value,s1[size].user);
printf("%s\n",s1[size].command);
size++;
}
fclose(file);
return 0;
}
I wanted to pick data from my file which contains the below information and I store it in specific portions of my structure array
a,w,a
r,e,1
i.e. if I store
a in s1[0].command
w in s1[0].value
a in s1[0].user
and
r in s1[1].command
e in s1[1].value
1 in s1[1].user
But when I try running my code it prints
a, w, a in s1[0].command
and
r, e, 1 in s1[1].command
so I am kindly requesting for help because I have tried googling but I couldn't get a solution.
The "%s" format reads space-separated "words".
If there isn't a space separating the "words" you have to use some other way to parse the input. For example by reading the whole line and then use something like strtok to "tokenize" the string.
Or make sure that the input format is space-separated.

Check if a file is empty or not

How can I check if a text file has something written or not. I tried:
LOGIC checkfile(char * filename)
{
FILE *pf;
pf=fopen(filename,"wt");
fseek(pf,0,SEEK_END);
if(ftell(pf)==0)
printf("empty");
}
This function returns empty everytime, even in my text file I have few words or numbers written.
The problem is that you opened the file for writing. When you do that, everything in the file is lost, and the length of the file is truncated to 0.
So you need to open the file for reading. And the easiest way to see if the file is empty is to try to read the first character with fgetc. If fgetc returns EOF, then the file is empty.
First of all: DO NOT OPEN THE FILE FOR WRITING!
second: for knowing about file status in C you can use fstat which is in sys headear file!
You can use struct stat for using this function
here is a simple example:
#include <sys/stat.h>
int main(void)
{
int fields = 0;
int size = 0;
// Open the file test.txt through open()
// Note that since the call to open directly gives
// integer file descriptor so we used open here.
// One can also use fopen() that returns FILE*
// object. Use fileno() in that case to convert
// FILE* object into the integer file descriptor
if(fields = open(file_path, "r")){
struct stat buf;
fstat(fields, &buf);
size = (int)buf.st_size;
}
printf("size of file is %d", size);
return 0;
}
Note: I just include a header file that related to fstat. You can add other header files yourself
What about using fscanf to read the file, and check if something was actually read?
FILE *fp;
char buff[255] = "";
fp = fopen(filename, "r");
fscanf(fp, "%s", buff);
if (!*buff)
printf("Empty\n");
else
printf("%s\n", buff);
fclose(fp);

C - Terminal Write and Output to a Text File

I am a student taking an introductory C course and have our first C midterm coming up. Our test environment would store our actions and printf output to a text file. However, our TA suggested we write to a file ourselves using fprintf just in-case.
Is there a very simple way I can copy my terminal/console output and input (what I enter in after scanf) to a text file like output.txt?
I tried
freopen("output.txt","w",stdout);
but that won't write my scanf input to the text file.
Can anyone help?
Don't use scanf();
Use fgets();
An example:
#include <stdio.h>
#include <stdlib.h>
#define Contents_Size 1000
int main()
{
char contents[Contents_Size];
//Opening the file
FILE * fp;
fp = fopen("\myfile.txt", "w"); //"w" = write
//If there is an error
if(fp == NULL)
{
//Exit
printf("Error!\n");
exit(EXIT_FAILURE);
}
//This part require your input
printf("Enter the contents of file: \n");
fgets(contents, Contents_Size, stdin);
//Write your input in file
fputs(contents, fp);
//Close the file
fclose(fp);
return 0;
}
fgest() will copy your input in contents[] and fputs() will paste every char of contents[] in your file.

Copy a file in C

I try to copy a file in a new file but it doesn't work because the input is 5133KB and the output is 614byte... what's wrong? Thank you in advance.
#include <stdio.h>
int main(void)
{
FILE * input = fopen("input.wav", "r");
FILE * output = fopen("output.wav", "w");
char buffer;
int bytesRead = 1;
while(bytesRead=fread(&buffer,1,1,input))
{
fwrite(&buffer,1,1,output);
}
fclose(input);
fclose(output);
return 0;
}
You may need to open the file in binary mode on your system. From C.2011, ยง7.21.5.3:
rb open binary file for reading
wb truncate to zero length or create binary file for writing
So:
FILE * input = fopen("input.wav", "rb");
FILE * output = fopen("output.wav", "wb");
The reason is that on some systems, certain embedded binary characters may cause the text mode processing to believe the end of file has been encountered, even though there are actually more bytes in the file.

fwrite creates an output file that is bigger than the input file

I want to read a file bytewise into an array and then write the data of the array reversed
in a new file (program takes filename over command line argument). Tried it with an txt-file
and it worked, but if I try it on a jpg-file the new file is bigger than the original!
The determined file size saved in long size; is also correct for jpg-files and write loop
get size-time executed writing one char (char is one byte big, I am right?).
Does anybody know how the output file can get bigger than size*byte?
It doesn't seem logical to me!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char* argv[])
{
FILE *file;
char *buffer;
long size;
char filename[32];
if(argc>1)
{
//determine file size
file=fopen(argv[1],"r");
fseek(file,0,SEEK_END);
size=ftell(file);
rewind(file);
if(size>33554432) //32MB
{
fclose(file);
return 0;
}
//create buffer and read file content
buffer=malloc(33554432);
fread(buffer,1,size,file);
fclose(file);
//create new file name and write new file
strcpy(filename,argv[1]);
strcat(filename,"_");
file=fopen(filename,"w");
{
long i;
for(i=size-1;i>=0;i--)
{
fputc(buffer[i],file);
}
}
fclose(file);
free(buffer);
}
return 0;
}
The comments you're receiving are implying something: the newline character \n works differently in text mode on Windows compared with some other systems.
fputc('\n', file) on Windows actually writes two bytes if file was opened in text mode "w", as if you did fwrite("\r\n", 1, 2, file). This means for any \n byte read by fread, you're writing two bytes back.
If you want to write binary data back, you need to open your output file using the mode "wb" to fopen(). You also need to open it for reading in binary mode, "rb".

Resources