How can I read with fread the content of file? - c

given the following text-file ("file_text);
example text
I'm trying to read the content of this file in this way:
#include <stdio.h>
#include <stdlib.h>
int main(){
char* arr = malloc(64);
FILE* f_fd = fopen("file_txt", "r");
fread(arr, 1, 64, f_fd);
printf("|%s|\n", arr);
return 0;
}
but it doesn't print the really content of the file. I see for example: |P?p| or |P^2| ..
And I don't understand why I get it.
NOTES: 64 is the max size of this file.

The name of your file is "file_text", but you trying to open this file with:
fopen("file_txt", "r");
try to open it with "file_text" file name.

Related

Manually copy a PNG file using fgetc() and fputc() in C

I am trying to manually copy a PNG file by reading individual bytes (chars) from one file, and then using fputc() to place them into another file. This is essentially a proof of concept as the end goal is to deconstruct the file into a byte stream that can be sent to a socket and then the client on the other side can reconstruct the image. Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *fp;
fp = fopen("picture.PNG", "rb");
fseek(fp, 0, SEEK_SET); // seek to beginning of file
FILE *wfp;
wfp = fopen("copy.PNG", "w");
int c;
while(TRUE){
c = fgetc(fp);
if (feof(fp)){
break;
}
fputc(c, wfp);
}
fclose(wfp);
fclose(fp);
return 0;
}
The resulting PNG file seems to be a copy of the original in that it has the same/similar size and when opening it in notepad and comparing to the original they look the same. However, I can't open it as a PNG and see the original image, which is the whole point.
How do I fix this code or what is the right way to accomplish my goal? Thanks.

convert Ascii code file into binary file

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?

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".

Read text into C. Get a bad exec error

Trying to learn C. Want to read the first line of a text file, my code is:
#include <stdio.h>
int main()
{
FILE *in = fopen("test.txt", "rt");
// read the first line from the file
char buffer[100];
fgets(buffer, 20, in);
printf("first line of \"test.txt\": %s\n", buffer);
fclose(in);
return 0;
}
I'm doing this in xCode. I get a exc bad access error.
test.txt definitely exists. It has one line that says "this is a text file"
try this after fopen() call:
if(in == NULL){
printf("Can't read teste.txt because: %s.\n", strerror(errno));
return 1;
}
and add the headers:
#include <errno.h>
#include <string.h>
The code looks fine, so my guess is that the program is not run in the same working directory as the file. Try placing the file in, say, /tmp/test.txt and use absolute path in fopen.
You don't check if the FILE is NULL. It may not be opened for a several reasons.

How to read text lines in C

I need to get lines from a text file. I already know that the lines won't be longer than 70 chars.
I have an idea about how to do it, but I'm looking a standard solution.
Maybe something like this ?
char line[MAXLEN];
while(fgets(line, sizeof(line), fp)) {
/* Do something with line. */
}
Don't forget that if you're reading in a file you need to have a file pointer and indicate what you want to do with the file. i.e. r -> read, w-> write. So it looks like you want to read the file.
So.....
Usage: gcc read.c -o read
"read input.txt"
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[] ){
FILE *fp;
char buffer[70];
fp = fopen(argv[1], "r");
while(fgets(buffer,70,fp) != NULL){
puts(buffer);
}
fclose(fp);
}
This takes in the file input.txt from the command line, puts it in the char buffer, prints it, and repeats until end of file.
Cheers

Resources