I'm trying to write a code in C to read binary files from the command line using linux. The specifications on reading the file are as follows:
*The name of the input file is to be passed into the program as a command line argument.
*The program will open this binary file and read the first integer in the file. It will then dynamically create an array of floats of this size using the malloc function.
*The program will then read the floating point values and store them into this newly crated array.
The only thing I've been able to do successfully is open the file.I previously tried to allocate a block of memory by doing
file=double*malloc(30*sizeof(double));
But I kept getting errors and ran into some serious problems when trying to put file in the *ptr parameter of the fread fucntion
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
This is what I have so far:
#include <stdio.h>
int main ( int argc, char *argv[] )
{
if ( argc != 2 )
{
printf( "usage: %s filename", argv[0] );
}
else
{
FILE *file = fopen( argv[1], "r" );
if ( file == 0 )
{
printf( "Could not open file\n" );
}
else
{
int x;
while ( ( x = fgetc( file ) ) != EOF )
{
printf( "%c", x );
}
fclose( file );
}
}
}
ptrparameter is supposed to be? Why would you think thefilegoes into theptrparameter rather than thestreamparameter? Even if you didn't read the man page the type tells you that. Please read the man page carefully first as it does answer your specific question. Come back to ask when you have done that due diligence and am still unclear.filefor both the open file stream and the data buffer. One in the actual code and one in the question description. That can't be the case in your actual code so please clarify your exact code and what the exact error is for that code.