LinuxQuestions.org
Register a domain and help support LQ
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices

Reply
 
Search this Thread
Old 04-21-2004, 03:17 PM   #1
Scrag
Member
 
Registered: Mar 2004
Location: Wisconsin
Distribution: Kali Linux
Posts: 122

Rep: Reputation: 15
C, howto read binary file into buffer


Could somebody provide a complete example of code that shows how to read a binary file into a buffer/array in C. Im trying to use fread() but my C book doesnt give very understandable examples. Or if theres something better than fread thats cool too.

Thank You!!
 
Old 04-21-2004, 03:35 PM   #2
deiussum
Member
 
Registered: Aug 2003
Location: Santa Clara, CA
Distribution: Slackware
Posts: 895

Rep: Reputation: 32
This is just off the top of my head, so I may miss something, but here goes:

Code:
FILE *f;
unsigned char buffer[MAX_FILE_SIZE];
int n;

f = fopen("filename.bin", "rb");
if (f)
{
    n = fread(buffer, MAX_FILE_SIZE, 1, f);
}
else
{
    // error opening file
}
 
1 members found this post helpful.
Old 04-21-2004, 04:09 PM   #3
The_Nerd
Member
 
Registered: Aug 2002
Distribution: Debian
Posts: 540

Rep: Reputation: 32
Code:
void ReadFile(char *name)
{
	FILE *file;
	char *buffer;
	unsigned long fileLen;

	//Open file
	file = fopen(name, "rb");
	if (!file)
	{
		fprintf(stderr, "Unable to open file %s", name);
		return;
	}
	
	//Get file length
	fseek(file, 0, SEEK_END);
	fileLen=ftell(file);
	fseek(file, 0, SEEK_SET);

	//Allocate memory
	buffer=(char *)malloc(fileLen+1);
	if (!buffer)
	{
		fprintf(stderr, "Memory error!");
                                fclose(file);
		return;
	}

	//Read file contents into buffer
	fread(buffer, fileLen, 1, file);
	fclose(file);

	//Do what ever with buffer

	free(buffer);
}
 
2 members found this post helpful.
Old 04-21-2004, 04:18 PM   #4
Scrag
Member
 
Registered: Mar 2004
Location: Wisconsin
Distribution: Kali Linux
Posts: 122

Original Poster
Rep: Reputation: 15
Hhhhmmmmmm.....

With your code, it reads in (im guessing) first 4 bytes of data, which is what is happening with the different code blocks that i've written. The file is ok, its a .bmp file. The output when printing buffer is:

BMÂ

Where when I cat the file its:

BMÂ(*€                       etc... etc....etc.........etc........

If im reading on the file right, and displaying it with correctly with printf("%s", buffer) , i should get lots of output to screen. I tried a for loop to read it in char by char, and output is still BMÂ, and i kept an integer count with how many char's read, and its 4.
Heres the code u gave me (modified).....any other ideas??

THANKS!!

FILE *f;
unsigned char buffer[10000];
int n;

f = fopen("bmp.bmp", "rb");
n = fread(buffer, 10000, 1, f);
printf("%s\n", &buffer);
 
Old 04-21-2004, 04:26 PM   #5
itsme86
Senior Member
 
Registered: Jan 2004
Location: Oregon, USA
Distribution: Slackware
Posts: 1,246

Rep: Reputation: 58
You can't just print a binary buffer as a string. The reason is because if the binary data contains 8-bits in a row of 0's it's interpreted as a string-terminating NULL. So let's say your buffer looks like this:

011101010101010010000101000000000001111111010100010101100

The string interprets the 00000000 as the end of the string.

If you want to show the entire contents of the buffer, then show each character one at a time until the counter equals the size of the file.

Code:
void dump_buffer(void *buffer, int buffer_size)
{
  int i;

  for(i = 0;i < buffer_size;++i)
     printf("%c", ((char *)buffer)[i]);
}

Last edited by itsme86; 04-21-2004 at 04:30 PM.
 
Old 04-21-2004, 04:32 PM   #6
Scrag
Member
 
Registered: Mar 2004
Location: Wisconsin
Distribution: Kali Linux
Posts: 122

Original Poster
Rep: Reputation: 15
COOL!!!

It works now, thanks to all of you !!!!!
 
Old 04-21-2004, 07:59 PM   #7
aluser
Member
 
Registered: Mar 2004
Location: Massachusetts
Distribution: Debian
Posts: 557

Rep: Reputation: 42
You can also use fwrite to print the whole thing with one function call -- it's similar to fread. (Use stdout as the FILE*)
 
Old 04-21-2004, 08:58 PM   #8
deiussum
Member
 
Registered: Aug 2003
Location: Santa Clara, CA
Distribution: Slackware
Posts: 895

Rep: Reputation: 32
Usually I find it's more useful to display binary data in a hexidecimal format. You can use something like:

Code:
for (int c=0;c<bufferSize;c++)
{
     printf("%.2X ", (int)buffer[c]);

     // put an extra space between every 4 bytes
     if (c % 4 == 3)
     {
         printf(" ");
     }

     // Display 16 bytes per line
     if (c % 16 == 15)
     {
         printf("\n");
     }
}
// Add an extra line feed for good measure
printf("\n");
Of course, you can also add extra stuff in there to make it look more like a hex editor as well, but you get the idea...
 
Old 01-16-2008, 09:34 AM   #9
knockout_artist
Member
 
Registered: Sep 2005
Distribution: fedora core 9
Posts: 324

Rep: Reputation: 33
Quote:
Originally Posted by The_Nerd View Post
Code:
void ReadFile(char *name)
{
	FILE *file;
	char *buffer;
	unsigned long fileLen;

	//Open file
	file = fopen(name, "rb");
	if (!file)
	{
		fprintf(stderr, "Unable to open file %s", name);
		return;
	}
	
	//Get file length
	fseek(file, 0, SEEK_END);
	fileLen=ftell(file);
	fseek(file, 0, SEEK_SET);

	//Allocate memory
	buffer=(char *)malloc(fileLen+1);
	if (!buffer)
	{
		fprintf(stderr, "Memory error!");
                                fclose(file);
		return;
	}

	//Read file contents into buffer
	fread(buffer, fileLen, 1, file);
	fclose(file);

	//Do what ever with buffer

	free(buffer);
}
Good Day,
How do I read the buffer??
I have tried looping through it But I didn't any out put.

Thanks.
 
Old 09-23-2009, 12:38 AM   #10
kishorworld
LQ Newbie
 
Registered: Sep 2009
Posts: 1

Rep: Reputation: 0
Smile How to Read Binary data file through C language

Hi friends....

m having a weather report file with extension as .wlk
it's a formatted binary data file...

Can anyone tell me that how to read this .wlk file and convert the data into the text format (.txt)with the help of C/C++ code ...

if possible provide me source code or usefule links to create programme

Email ID: kishor.j@ncmsl.com

thanx in advance...

Last edited by kishorworld; 09-23-2009 at 12:39 AM. Reason: providing email id
 
Old 09-23-2009, 12:51 AM   #11
smeezekitty
Senior Member
 
Registered: Sep 2009
Location: Washington U.S.
Distribution: M$ Windows / Debian / Ubuntu / DSL / many others
Posts: 2,230

Rep: Reputation: 173Reputation: 173
Quote:
Originally Posted by kishorworld View Post
Hi friends....

m having a weather report file with extension as .wlk
it's a formatted binary data file...

Can anyone tell me that how to read this .wlk file and convert the data into the text format (.txt)with the help of C/C++ code ...

if possible provide me source code or usefule links to create programme

Email ID: kishor.j@ncmsl.com

thanx in advance...
your problem is more complicated
please start your own thread
 
Old 09-23-2009, 10:13 AM   #12
theNbomr
LQ 5k Club
 
Registered: Aug 2005
Distribution: OpenSuse, Fedora, Redhat, Debian
Posts: 5,395
Blog Entries: 2

Rep: Reputation: 903Reputation: 903Reputation: 903Reputation: 903Reputation: 903Reputation: 903Reputation: 903Reputation: 903
Use the code posted by deiussum in article #8 of this thread. That won't interpret the file in any way, but simply display the bytes as hexadecimal. Interpretation of the data is application specific, and most people here won't know how to extract meaningful information from files of that type. For that, you will need some kind of published documentation, or a code library/API written for the purpose of interpreting the file.
--- rod.
 
Old 09-23-2009, 12:44 PM   #13
smeezekitty
Senior Member
 
Registered: Sep 2009
Location: Washington U.S.
Distribution: M$ Windows / Debian / Ubuntu / DSL / many others
Posts: 2,230

Rep: Reputation: 173Reputation: 173
did you see how many views on this thread?! LOL
 
Old 01-14-2010, 06:40 AM   #14
naphstor
LQ Newbie
 
Registered: Jan 2010
Posts: 3

Rep: Reputation: 0
reading a .m4v file.

hi all, i am a newbie in this forum. luckily i got the post i was searching for. but i have some issues. i have a .m4v file and want to read it and display its contents. i read the file and tried to print the buffer, but got some junk data on screen. i even tried the code given above for printing buffer, but effort seems to be in vain. The above modified code i used is :-


Code:
#include <stdio.h>

main()
{
	FILE *file;
	char *buffer;
	unsigned long fileLen;

	file = fopen("1.m4v", "rb");
	if (!file)
	{
		fprintf(stderr, "can't open file %s", "1.m4v");
		exit(1);
	}

	fseek(file, 0, SEEK_END);
	fileLen=ftell(file);
	fseek(file, 0, SEEK_SET);

	buffer=(char *)malloc(fileLen+1);

	if (!buffer)
	{
		fprintf(stderr, "Memory error!");
        fclose(file);
		exit(1);
	}

	fread(buffer, fileLen, 1, file);
	fclose(file);

	printf ("value is %s \n", &buffer);
	dump_buffer(&buffer, fileLen);
	//free(buffer);
}

dump_buffer(void *buffer, int buffer_size)
{
  int i;

  for(i = 0;i < buffer_size;++i)
     printf("%c", ((char *)buffer)[i]);
}
please help me out. thanks.
 
Old 01-14-2010, 08:24 AM   #15
Sergei Steshenko
Senior Member
 
Registered: May 2005
Posts: 4,481

Rep: Reputation: 453Reputation: 453Reputation: 453Reputation: 453Reputation: 453
Quote:
Originally Posted by naphstor View Post
hi all, i am a newbie in this forum. luckily i got the post i was searching for. but i have some issues. i have a .m4v file and want to read it and display its contents. i read the file and tried to print the buffer, but got some junk data on screen. i even tried the code given above for printing buffer, but effort seems to be in vain. The above modified code i used is :-


Code:
#include <stdio.h>

main()
{
	FILE *file;
	char *buffer;
	unsigned long fileLen;

	file = fopen("1.m4v", "rb");
	if (!file)
	{
		fprintf(stderr, "can't open file %s", "1.m4v");
		exit(1);
	}

	fseek(file, 0, SEEK_END);
	fileLen=ftell(file);
	fseek(file, 0, SEEK_SET);

	buffer=(char *)malloc(fileLen+1);

	if (!buffer)
	{
		fprintf(stderr, "Memory error!");
        fclose(file);
		exit(1);
	}

	fread(buffer, fileLen, 1, file);
	fclose(file);

	printf ("value is %s \n", &buffer);
	dump_buffer(&buffer, fileLen);
	//free(buffer);
}

dump_buffer(void *buffer, int buffer_size)
{
  int i;

  for(i = 0;i < buffer_size;++i)
     printf("%c", ((char *)buffer)[i]);
}
please help me out. thanks.

What kind of data do you expect on the screen and why do you expect it to look not like junk ? I.e. do you know what data is displayed on screen as something meaningful and what data as junk/gibberish ? If I may, have you ever heard of ASCII ? If not, try to perform web search on ASCII and/or try

man ascii

on your UNIX/Linux bix.
 
1 members found this post helpful.
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
read & write binary file error in redhat xcmore Programming 11 06-17-2005 07:48 AM
convert text file to binary excel file ust Linux - General 2 11-23-2004 02:33 AM
tcp/ip read and write buffer da_kidd_er Linux - Software 0 11-21-2004 04:13 PM
NULL buffer in read sys call unpredictable jwstric2 Programming 3 09-02-2004 07:13 PM
howto disable/correct frame buffer? Distorts boot screen... BroX Debian 3 08-16-2004 03:02 AM


All times are GMT -5. The time now is 10:28 PM.

Main Menu
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration