Coredump in fread when pointing to file in array - c

Recently started working with pointers and have created a little script that is supposed to stich together some textfiles.
However when i try to call fputs i get a coredump/segmentation error. I suspect it is because of the way that the file pointer is saved. I find the files saves it in an array and tries to retrieve it later on.
the FILE pointer is saved in a struct. Does somebody instantly spot my fault? i would be very grateful!
The struct:
typedef struct{
int listSize;
int listCapacity;
FILE *fileStream;
}FileList;
Creating the struct
FileList fileList;
fileList.listSize=0;
fileList.listCapacity=1;
fileList.fileStream=calloc(fileList.listCapacity,sizeof(FILE));
and then i add the struct to the array by calling
void addFile(FileList* list, FILE* file)
{
list->fileStream[list->listSize]=*file;
}
However when i call
char* buffer[10];
size_t result=0;
result = fread(buffer,1,10,&fileList.fileStream[ii+currentGroupOffset]);
fputs(*buffer,outPutFile);
it crashes, i tried to watch the value ii+currentGroupOffset making sure it doesnt go out the array bounds
any help at all appriciated! :)

You can't allocate and copy around FILE structures yourself - it's an opaque data type. So, instead of creating an array of FILE structures, create an array of FILE * pointers:
typedef struct {
int listSize;
int listCapacity;
FILE **fileStream;
} FileList;
FileList fileList;
fileList.listSize = 0;
fileList.listCapacity = 1;
fileList.fileStream = calloc(fileList.listCapacity, sizeof fileList.fileStream[0]);
then add a FILE * pointer to the array by copying the pointer value:
void addFile(FileList *list, FILE *file)
{
list->fileStream[list->listSize] = file;
}
and use it like so:
char buffer[10];
size_t result = 0;
result = fread(buffer, 1, 10, fileList.fileStream[ii+currentGroupOffset]);
fwrite(buffer, 1, result, outPutFile);

It seems you want a dynamically allocated array of FILE* elements. You have:
FILE *fileStream;
That can either be treated as a FILE pointer, or an array of FILE elements. But not as an array of FILE pointers. For that, you need:
FILE **fileStream;
And allocating the array should be done with:
fileList.fileStream=calloc(fileList.listCapacity,sizeof(FILE*));
FILE is not a type you use directly. You always deal with pointers to it. You should treat it as an opaque type.
Also, I don't see where you actually open the files (using fopen()) anywhere in your code.

Why
char * buffer[10];
It should be
char buffer[10];
Where is list->listSize incremented?
I don't understand what this is
fileList.fileStream=calloc(fileList.listCapacity,sizeof(FILE));
FILE *s are initialized by calling fopen not by allocating memory

Related

How can I write an array of struct of 20 structs despite not being entirely populated?

This is my struct:
typedef struct file {
char name[20];
int size;
int offset;
} file;
So basically I'm writing
4bytes for num of files
array of structs --> each 28 bytes
contents of files
// writing num of files
fwrite(&numFiles, sizeof(numFiles), 1, binFile);
size_t bytesW = 0;
for (int i = 0; i < MAX; i++) {
// writing structs of information
bytesW += fwrite(list, sizeof(file), 1, binFile);
}
printf("bytes written: %d\n", bytesW);
fclose(binFile);
Is it possible to write the entire array, if I only have a couple struct elements filled? I want to do this so that whenever I want to add new elements I can fseek into the end of dir with sizeof(file) * numFiles.
EDIT This is for a binary file
Yes, it is possible to write your entire array to a file even if only some of it is filled with meaningful data.
To avoid undefined behavior, I recommend that you at least initialize everything in the array before writing it to the file. You can simply run memset after allocating the memory for the array in order to initialize everything to 0, or if your array is allocated as a global variable then it will get initialized to 0 automatically.
The code you provided looks like it just writes the same element every time. Maybe you meant to use &list[i] instead of list.

C: Saving dynamic array of structs along with string

I am trying to save a struct (listed)
typedef struct tupleStruct{
int element[eMax];
char * id;
int eCount;
}tuple_t;
typedef struct {
tuple_t * array;
int used;
int size;
} DynamicArray;
As part of an assignment I was instructed to save tuples that are stored in a dynamic array in a file. Unfortunately since strings don't exist in c (at least not like they do in other languages). Whenever I try to save an element of the dynamic array in a file, the string is not stored or loaded properly as it's seen as a pointer. I've even tried by initializing it like so in the struct:
char id[256];
Is there any way possible to save the struct and the string in a single file? (Given that I need to store multiple of these)
Edit: Saving and loading code
Loading
DynamicArray loadAllTuples(){
FILE *filePointer;
DynamicArray tempArray;
if((filePointer=fopen("SavedTuples.bin","rb"))==NULL)
{
fputs("Something went wrong while loading!\nA blank Array will be loaded instead\n", stderr);
setbuf(stdout, 0);
//In case of error, blank array is initalised and loaded
fclose(filePointer);
intialiseDynamicArray(&tempArray);
return tempArray;
}
fread(&tempArray, sizeof(DynamicArray),1,filePointer);
//Freeing filePointer memory
free(filePointer);
return tempArray;
}
saving
void saveAllTuples(DynamicArray ToSave){
trimArray(&ToSave,0); //Removing extra space from array
FILE * filePointer;
if((filePointer=fopen("SavedTuples.bin","wb"))==NULL)
{
fputs("Something went wrong while saving!\n", stderr);
setbuf(stdout, 0);
return;
}
fwrite(&ToSave, sizeof(ToSave), 1,filePointer);
fclose(filePointer);
}
called by
saveAllTuples(dynaArray);
and
dynaArray=loadAllTuples();
Instead of writing the whole struct in one go, write out the various parts of it utilising your knowledge of what they contain. So for example, if eCount is the amount of values in element you could write this
fwrite(&ToSave.eCount,sizeof(int), 1, filepointer);
fwrite(ToSave.element,sizeof(int), ToSave.eCount, filepointer);
and then to store the string component
size_t length=strlen(ToSave.id);
fwrite(&length,sizeof(int), 1, filepointer);
fwrite(ToSave.id,sizeof(char), length, filepointer);
Note: sizeof(char) is typically always 1, so you could assume that and put 1 rather than sizeof(char) but I find it makes the code look more uniform to leave it in.
And then you reverse the process when you do the reading
fwrite(&ToLoad.eCount,sizeof(int), 1, filepointer);
fwrite(ToLoad.element,sizeof(int), ToLoad.eCount, filepointer);
// etc...
To whom it may help in the future: So after asking around a bit, some people got it to work by treating the identifier as an array instead of a pointer.
char id[256];
I said this didn't work before, but it was probably due to another mistake which I didn't spot. Saving each tuple will keep the string identifier intact as long as an array is used.

Scanning into structs

I want to ultimately insert strings from a file into elements in structs and can't get it right. Can you see what is wrong here?
int main()
{
FILE *fp;
char file_name[10] = "map7.map";
fp = fopen(file_name,"r");
int a = 1;
int *pnumberOfRows = &a;
fscanf(fp,"%d",pnumberOfRows);
typedef struct {
bool visited;
char *cityName;
} map;
map *ver = malloc(sizeof(map)*2*(*pnumberOfRows));
fscanf(fp,"%s",ver[1].cityName);
printf("%s",ver[1].cityName);
return 0;
}
It seems like you're simply missing to allocate space for the char *cityName fields, which makes you fscanf onto an unallocated pointer. You could either provide a fixed-with field, e.g.
typedef struct {
bool visited;
char cityName[81];
} map;
for a maximum length of 80 characters (i.e. excluding \0) or determine the length of the city names in the file beforehand and then allocating memory to the field using
ver[0]->cityName = (char*)malloc(sizeof(char)*(stringLength+1));
Note that sizeof(char) == 1, so feel free to leave it away, but see the answers here for more information. I left it here for the sake of being expressive about what you want to achieve.
Also, don't forget to free the memory you malloc'd at the end and also close the file descriptor after you're done (i.e. fclose(fp);).

read / write structures to file - c

I'm working on creating a student database in C. The final thing I need to be able to do read and write the database I create to a file. So I've already got an array full of pointers to student structures, and I need to write it to a file. Once I have it written, I need to be able to read it back into my array as well.
I'm really not sure how to do it though. This is my struct:
typedef struct student Student;
struct student
{
char name[300];
int age;
char course1[300];
char course2[300];
char remarks[300];
};
Student *Data[30];
And these are the functions I've written to work with file:
void writeDisk()
{
FILE *file = fopen("disk.dat", "ab");
fwrite(&Data, sizeof(Student), count, file);
fclose(file);
}
void loadDisk()
{
FILE *file = fopen("disk.dat", "rb");
if (file != NULL)
{
fread(&Data, sizeof(Student), count, file);
fclose(file);
}
}
void emptyDisk()
{
FILE *file = fopen("disk.dat", "rw");
fopen("disk.dat", "wb");
}
I can see that the size of my disk.dat file changes when I write to it, and it goes to zero when I call empty, but loading does not work at all. If the student array in my program is zero, it just stays at zero when I call load and try to display it, but if there is something in the array, I get a segmentation fault when I call load and then try to display it.
I may be doing this entirely wrong. I'm really not sure what I'm doing. I was thinking that I could just write the whole array to a file, but I'm not sure that's true. I was just wondering if someone could look at this and let me know where I'm going wrong.
EDIT
I've edited my code to look like this:
void writeDisk()
{
int i = 0;
FILE *file = fopen("disk.dat", "ab");
for(i; i <count; i++)
{
fwrite(Data[i], sizeof(Student), 1, file);
}
fclose(file);
}
void loadDisk()
{
char buffer[300];
int i = 0;
clearData();
FILE *file = fopen("disk.dat", "rb");
while(Data[i] != NULL)
{
Data[i] = malloc(sizeof(Student));
fread(Data[i], sizeof(Student), 1, file);
i++;
}
fclose(file);
}
This still doesn't work though. The write seems to work better,but I don't see it writing the age of the student over to the file. The clearData() function in the load file just clears anything that's in the Data array to begin with, so that we can have a clean slate to read the file into.
I believe instead of
Student *Data[30];
You want
Student Data[30];
Because the first one is an array of pointers, while the second one is an array of the struct you want.
When you write
fread(&Data, sizeof(Student), count, file);
It reads the data from the file right into the location of Data. It looks like you want to read and write the actual structs, so you have to put them directly into the array, as opposed to using pointers.
I think this is the culprit:
Student *Data[30];
That's an array of pointers to Student structures. There is no storage allocated for actual Students.
Remove the *, throughout the rest of the code you seem to properly use Data as if it was a plain array, so it should need no modification.
EDIT on an unrelated note, you can declare a structure and its alias on the same statement, like this:
typedef struct {
...
} Student;
If Data is indeed an array of pointers to your structures, then what you are saving is just the pointers and not your actual data. In fact, you should never save actual pointers as the next time you run, malloc may return different pointers for storing your data.
What you want to do, for saving, is to iterate over your array and write the actual structure data to the file, something like:
for (i = 0; i < numberOfStudents; i++) {
fwrite(Data[i], sizeof (Student), 1, file);
}
For restoring, you'll need to loop over the students, malloc storage and read in the structure, and then set the Data pointer, something like:
for (i = 0; i < numberOfStudents; i++) {
Student *p = malloc(sizeof (Student));
fread(p, sizeof (Student), 1, file);
Data[i] = p;
}
Also, in general, you should check the return values from fopen, fread, fwrite, and fclose to detect errors.

Reading file and populating struct

I have a structure with the following definition:
typedef struct myStruct{
int a;
char* c;
int f;
} OBJECT;
I am able to populate this object and write it to a file. However I am not able to read the char* c value in it...while trying to read it, it gives me a segmentation fault error. Is there anything wrong with my code:
//writensave.c
#include "mystruct.h"
#include <stdio.h>
#include <string.h>
#define p(x) printf(x)
int main()
{
p("Creating file to write...\n");
FILE* file = fopen("struct.dat", "w");
if(file == NULL)
{
printf("Error opening file\n");
return -1;
}
p("creating structure\n");
OBJECT* myObj = (OBJECT*)malloc(sizeof(OBJECT));
myObj->a = 20;
myObj->f = 45;
myObj->c = (char*)calloc(30, sizeof(char));
strcpy(myObj->c,
"This is a test");
p("Writing object to file...\n");
fwrite(myObj, sizeof(OBJECT), 1, file);
p("Close file\n");
fclose(file);
p("End of program\n");
return 0;
}
Here is how I am trying to read it:
//readnprint.c
#include "mystruct.h"
#include <stdio.h>
#define p(x) printf(x)
int main()
{
FILE* file = fopen("struct.dat", "r");
char* buffer;
buffer = (char*) malloc(sizeof(OBJECT));
if(file == NULL)
{
p("Error opening file");
return -1;
}
fread((void *)buffer, sizeof(OBJECT), 1, file);
OBJECT* obj = (OBJECT*)buffer;
printf("obj->a = %d\nobj->f = %d \nobj->c = %s",
obj->a,
obj->f,
obj->c);
fclose(file);
return 0;
}
When you write your object, you're writing the pointer value to the file instead of the pointed-to information.
What you need to do is not just fwrite/fread your whole structure, but rather do it a field at a time. fwrite the a and the f as you're doing with the object, but then you need to do something special with the string. Try fwrite/fread of the length (not represented in your data structure, that's fine) and then fwrite/fread the character buffer. On read you'll need to allocate that, of course.
Your first code sample seems to assume that the strings are going to be no larger than 30 characters. If this is the case, then the easiest fix is probably to re-define your structure like this:
typedef struct myStruct{
int a;
char c[30];
int f;
} OBJECT;
Otherwise, you're just storing a pointer to dynamically-allocated memory that will be destroyed when your program exits (so when you retrieve this pointer later, the address is worthless and most likely illegal to access).
You're saving a pointer to a char, not the string itself. When you try to reload the file you're running in a new process with a different address space and that pointer is no longer valid. You need to save the string by value instead.
I would like to add a note about a potential portability issue, which may or may not exist depending upon the planned use of the data file.
If the data file is to be shared between computers of different endian-ness, you will need to configure file-to-host and host-to-file converters for non-char types (int, short, long, long long, ...). Furthermore, it could be prudent to use the types from stdint.h (int16_t, int32_t, ...) instead to guarantee the size you want.
However, if the data file will not be moving around anywhere, then ignore these two points.
The char * field of your structure is known as a variable length field. When you write this field, you will need a method for determining the length of the text. Two popular methods are:
1. Writing Size First
2. Writing terminal character
Writing Size First
In this method, the size of the text data is written first, followed immediately by the data.
Advantages: Text can load quicker by block reads.
Disadvantages: Two reads required, extra space required for the length data.
Example code fragment:
struct My_Struct
{
char * text_field;
};
void Write_Text_Field(struct My_Struct * p_struct, FILE * output)
{
size_t text_length = strlen(p_struct->text_field);
fprintf(output, "%d\n", text_length);
fprintf(output, "%s", p_struct->text_field);
return;
}
void Read_Text_Field(struct My_STruct * p_struct, FILE * input)
{
size_t text_length = 0;
char * p_text = NULL;
fscanf(input, "%d", &text_length);
p_text = (char *) malloc(text_length + sizeof('\0'));
if (p_text)
{
fread(p_text, 1, text_length, input);
p_text[text_length] = '\0';
}
}
Writing terminal character
In this method the text data is written followed by a "terminal" character. Very similar to a C language string.
Advantages: Requires less space than Size First.
Disadvantages: Text must be read one byte at a time so terminal character is not missed.
Fixed size field
Instead of using a char* as a member, use a char [N], where N is the maximum size of the field.
Advantages: Fixed sized records can be read as blocks.
Makes random access in files easier.
Disadvantages: Waste of space if all the field space is not used.
Problems when the field size is too small.
When writing data structures to a file, you should consider using a database. There are small ones such as SQLite and bigger ones such as MySQL. Don't waste time writing and debugging permanent storage routines for your data when they have already been written and tested.

Resources