GoAskAlice
Programmer
Basically, I am learning C under Linux. What I am attempting is fwrite and fread functions on a file.
The write program works without fault, but when I try and read the data back from the file, the data is displayed, but then at the end of it all it states 'Segmentation fault'.
So, here is the code...can anyone help?
write file.c
----------------------------------------------------------
// Write to file using fwrite
#include <stdio.h>
int main() {
FILE *fp;
int writecount = 0;
int a[4];
a[0] = 12345678;
a[1] = 23456789;
a[2] = 34567891;
a[3] = 45678912;
if (( fp = fopen( "items.txt", "w" )) == NULL ){
perror ( "Opening data file" ); return -1;
}
writecount = fwrite( a, sizeof (a), 8, fp );
if ( fclose(fp) != 0)
{
fprintf(stderr, "Error closing file.\n");
return -2;
}
return 0;
}
----------------------------------------------------------
read file.c
-----------------------------------------------------------
// Read file using fread
#include <stdio.h>
int main() {
FILE *fp;
int a[4];
int readcount = 0;
int c;
if (( fp = fopen( "items.txt", "r+" )) == NULL){
perror( "Opening data file" );
return -1;
}
readcount = fread( a, sizeof( a ), 8, fp);
for( c = 0; c < 4; c++ ) {
printf("%i\n",a[c]);
}
if ( fclose(fp) != 0)
{
fprintf(stderr, "Error closing file.\n");
return -2;
}
return 0;
}
-----------------------------------------------------------
The write program works without fault, but when I try and read the data back from the file, the data is displayed, but then at the end of it all it states 'Segmentation fault'.
So, here is the code...can anyone help?
write file.c
----------------------------------------------------------
// Write to file using fwrite
#include <stdio.h>
int main() {
FILE *fp;
int writecount = 0;
int a[4];
a[0] = 12345678;
a[1] = 23456789;
a[2] = 34567891;
a[3] = 45678912;
if (( fp = fopen( "items.txt", "w" )) == NULL ){
perror ( "Opening data file" ); return -1;
}
writecount = fwrite( a, sizeof (a), 8, fp );
if ( fclose(fp) != 0)
{
fprintf(stderr, "Error closing file.\n");
return -2;
}
return 0;
}
----------------------------------------------------------
read file.c
-----------------------------------------------------------
// Read file using fread
#include <stdio.h>
int main() {
FILE *fp;
int a[4];
int readcount = 0;
int c;
if (( fp = fopen( "items.txt", "r+" )) == NULL){
perror( "Opening data file" );
return -1;
}
readcount = fread( a, sizeof( a ), 8, fp);
for( c = 0; c < 4; c++ ) {
printf("%i\n",a[c]);
}
if ( fclose(fp) != 0)
{
fprintf(stderr, "Error closing file.\n");
return -2;
}
return 0;
}
-----------------------------------------------------------