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;




}
 
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:
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:
Back
Top Bottom