reading a .dat file in c

Associate
Joined
19 Nov 2008
Posts
412
Location
carnmoney outside Belfast
Hey guys, need abit of help here. The task is to read data from a .dat file and output the results to the console.

My code compiles ok but when I run it nothing happens. I have a .dat file with a random number in it.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

main()
{
//Declaring variables
char File_size[100];
int a = 0;
int b;

//setting file pointer to read from .dat file
FILE *file_pointer = NULL;
file_pointer = fopen("exercise4.dat", "rb");


//loop through file reading data

while ((a = fgetc(file_pointer))!= EOF) //keep reading data until end of file
{
fread(&File_size,sizeof(a),1,file_pointer);
printf("%c\n", &File_size);
}

fclose(file_pointer);
return 0;




}
 
Two things. One, you're not checking for failure in the fopen() call, so if that fails, it's going to crash. Two, you're reading the same file twice - fgetc() and fread() - and worse, you're mixing up the buffers too. Unless you've got a good reason to be doing that, use one or the other - not both.

If the fgetc() was just there to test for EOF, then use feof() instead.
 
Thanks very much berserker. Ill look up the code for the failure check on fopen, shouldnt be too hard. Ill post back if I get stuck again.
 
How would you chang e the code so that a file name could be input from the console? Would it be

main()
{
//Declaring variables
char File_size[100];
char file_name[100];
int a = 0;
int b;

printf("input file name: ");
scanf("%s",&file_name);



//setting file pointer to read from .dat file
FILE *file_pointer = NULL;
file_pointer = fopen("&file_name", "rb");
 
Last edited:
probably easier using the argc and argv[] to access the command line parameters then you could run:

flibble% mybinary exercise4.dat
 
Ive got it working now (apart from inputting the file name from console should be able to get it eventually)

Ive never seen that other method. You wouldn't have an example or a link explaining it somewhere out of interest?
 
Last edited:
There is some info about it here: http://pages.cs.wisc.edu/~david/courses/cs354/onyourown/C.argv.html

Code would look something like:

Code:
int main(int argc,char *argv[])
{
    int i;
    printf("Number of arguments = %i", argc);

    // Note that argv[0] is the name of the executable, and 
    // so normally not checked.

    for( i=1 ; i<argc ; i++ ) 
        printf("Argument %i = %s", i, argv[i]);

    return(0);
}

EDIT: Made ANSI C compatible.
 
Last edited:
Code:
#include <stdio.h>

int main()
{
	char buffer[64];
	FILE *pDatFile = fopen( "datfile.dat", "r" );

	if( !pDatFile ) { puts("Error"); return 0; }

	while( fgets( buffer, 64, pDatFile ) ) { printf( "%s", buffer ); }

	fclose(pDatFile);
	return 0;
}
 
Back
Top Bottom