I have a code and my question is how to send structure array information to file and then scan it. I have some functions, but my function Write doens't write correctly to file.
typedef struct School
{
char Lesson[50];
char TeachersName[50];
char TeachersLastName[50];
int Credits;
int NumberOfStudents;
} School;
void Write(struct School sAmlendraInfor[]);
int main()
{
School sAmlendraInfor[MAX_SIZE] = {{"Math","NAME_A","LAST_NAME_A",120,60},
{"History","NAME_B","LAST_NAME_B",60,33}};
Scan(sAmlendraInfor);
Print(sAmlendraInfor);
Write(sAmlendraInfor);
}
void Write(struct School sAmlendraInfor[])
{
int chars;
FILE *fp;
fp = fopen("\student.bin", "wb");
if(fp == NULL)
{
printf("Error opening file\n");
exit(1);
}
chars = fwrite (&sAmlendraInfor, sizeof(School), 1, fp);
printf("Number of items written to the file: %d\n", chars);
fclose(fp);
}
Related
I'm trying to read a text file in C. And I want to put the info in a struct.
I think I'm reading the file correctly but when I have to print the info, all the data is filled by the last line of the text.
Do you know why?
#include <stdio.h>
#define MAXCHAR 1000
int main() {
struct lumi {
char *domini;
char *disponible;
};
struct lumi registre[256];
int i = 0;
FILE *fp;
char str[MAXCHAR];
char* filename = "fitxer.txt";
fp = fopen(filename, "r");
if (fp == NULL){
printf("Could not open file %s",filename);
return 1;
}
while (fgets(str, MAXCHAR, fp) != NULL){
registre[i].domini = str;
registre[i].disponible = "offline";
i = i+1;
}
printf("%s", registre[0].domini);
printf("%s", registre[1].domini);
printf("%s", registre[2].domini);
printf("%s", registre[3].domini);
fclose(fp);
return 0;
}
The .txt I tried is
Hi
My
Name
Is
Create a function to read a text file and transfer their name to a dynamic vector of structures.
I'm reading the file but it doesn't appear nothing on the screen.
typedef struct aluno student;
struct aluno{
char name[50], address[50], number[9];
int year;enter code here
};
student *lerFicheiroTexto(char *nameFile, int *tam){
FILE *f1;
student buffer;
student *aux;
student *vetor = NULL;
f1 = fopen(nameFile, "rt");
if(f1 == NULL){
printf("Error opening the file text");
return NULL;
}
while(fscanf(f1, "%s %s %d %s", buffer.name, buffer.address, &buffer.year, buffer.number) == 3){
printf("%s\t%s\n%d\n%s\n", buffer.name, buffer.address, buffer.year, buffer.number);
aux = realloc(vetor, sizeof(student)*(*tam+1));
if(aux == NULL){
//realocation failled
printf("Reallocation failled. Maintain tam \n");
(*tam) = 0;
return NULL;
}
else{
vetor = aux;
vetor[(*tam)] = buffer;
}
(*tam)++;
}
fclose(f1);
return vetor;
}
I would need to have your input file to test this but I changed your code a bit.
I'm also a student so my apologies if I've done something wrong.
From what I see, I believe your code could be improved like so:
Definition of struct:
typedef struct aluno {
char name[50], address[50], number[9];
int year;
} Aluno;
Function to read the file and build your array:
Aluno* lerFicheiroTexto(char* nameFile, int tamanho)
{
FILE* file = fopen(nameFile, "r");
if (file == NULL) {
printf("Error opening the file text");
return NULL;
}
Aluno* listaAlunos = malloc(sizeof(Aluno));
char line[255];
while (fgets(line, 255, file) != NULL) {
Aluno currAluno;
sscanf(line, "%s %s %d %s", currAluno.name, currAluno.address, currAluno.year, currAluno.number);
listaAlunos[tamanho] = currAluno;
listaAlunos = realloc(listaAlunos, sizeof(Aluno) * ++tamanho);
}
fclose(file);
return listaAlunos;
}
Im having a hard time inputting the data to the file, whenever I input data to struct array then saves it to text file, fwrite() prints nothing to the file.
int last;
struct Person{
int pid;
char lname[MAXchar], fname[MAXchar], mname[MAXchar];
int age;
char subject[MAXchar];
float grade;
};
struct Person Num[MAX];
struct Person *No;
and this is how I save it to the text file.
void saveDATA(){
FILE *fp;
fp=fopen("database.txt","ab");
fwrite(No, sizeof(struct Person), 1, fp);
if(fwrite != 0)
printf("Success!\n");
else
printf("error!\n");
fclose(fp);
}
Although the program says it returns, fwrite doesnt print any data at the text file
and this is how I load the data to return it to the struct array but its not working
void loadDATA(){
FILE *fp;
char line[500];
fp=fopen("database.dbf","rb+");
if(fp == NULL){
fp = fopen("database.dbf", "wb");
}
while (fgets(line, sizeof(line), fp)){
last++;
fscanf(line,"%d %s %s %s %d %s %2.f", &array[last].pid, array[last].lname, array[last].fname,array[last].mname, &array[last].age, array[last].subject, &array[last].grade);
insert(array.tempID, array.L, array.F, array.M, array.TempAge, array.Sub, array.Tempgrade);
}
fclose(fp);
}
I am trying to load a binary file but I am getting:
realloc(): invalid next size
This is the struct im using in the following code:
typedef struct {
int from;
int to;
int cost;
} edge_t;
typedef struct {
int size;
int capacity;
edge_t *edges;
} graph_t;
Code:
#include <stdlib.h>
#include <stdio.h>
#include "graph.h" //this is the struct above
void load_bin(const char *fname, graph_t *graph) {
graph->capacity = 1;
graph->size = 0;
graph->edges = malloc(graph->capacity*sizeof(edge_t));
FILE *myFile;
myFile = fopen(fname, "r");
if (myFile == NULL) {
fprintf(stderr, "Error: file not found!\n");
exit(100);
}
while(fread(&(graph->edges[graph->size].from), sizeof(edge_t), 3, myFile) == 3){
graph->size++;
if(graph->capacity == graph->size){
graph->capacity *=2;
graph->edges=realloc(graph->edges, sizeof(edge_t)*graph->capacity);
}
}
}
EDIT: Tried to make a verifiable example, as requested.
int main(int argc, char *argv[])
{
int ret = 0;
if (argc > 2) {
graph_t *graph = allocate_graph();
fprintf(stderr, "Load bin file '%s'\n", argv[1]);
load_bin(argv[1], graph);
fprintf(stderr, "Save txt file '%s'\n", argv[2]);
save_txt(graph, argv[2]);
free_graph(&graph);
} else {
fprintf(stderr, "Usage %s input_bin_file output_txt_file\n", argv[0]);
ret = -1;
}
return ret;
}
This function and load are located in the same file and are called from main
graph_t *allocate_graph(){
return calloc(1, sizeof(graph_t));
}
From what I checked, it means I do not change the size properly on realloc, but I thought i was?
Thanks.
the while is invalid, must be
while(fread(&(graph->edges[graph->size].from), sizeof(edge_t), 1, myFile) == 1)
because currently you read 3 elements and go out of the allocated memory
P.S. out of that, are you sure you read correctly the file ? you suppose the content is consecutive 3 values on sizeof(int) bytes, without separator etc
Anyone know how to read a text file into a struct array? I've been trying to figure out how to do so to no avail.
Here's the function header
int getRawData(FILE* fp, struct nameRecord records[], int currSize)
where the first parameter is passed a file already open for reading, the second an array of nameRecord structs, and the third the number of records currently in that array. The function is supposed to read the data from the file into the array placing it at the end of the array. It then returns the total number of records in the array after reading the file.
I'm also at a loss at initializing the number of elements for the nameRecord struct array. We've never been taught memory allocation and the problem doesn't make any mention of how many records are within the files, making initialization an excercise in frustration. So far, I'm taking advice from someone at another forum and using malloc, but I don't even really know what it does.
Some info on the program itself to provide context:
program will ask the user to enter a name (you may assume that the
name will be no more than 30 characters long). It will then find the
popularity of the name between 1921 and 2010 and print out a chart and
graph. The program will then ask the user if they wish to do another
analysis and repeat the process.
The program will pull information from the following data sources in
determining the popularity of a name.
ontario female baby names ontario male baby names
Note that some names are considered both male and female so your
program will needs the data from both files regardless of the name
entered.
My attempt at the function:
//function that reads and places the read files into the struct arrays
int getRawData(FILE* fp, struct nameRecord records[], int currSize) {
int i;
for(i = 0; i < currSize; i++) {
fscanf(fp, "%[^,],%d,%d", records[i].name, &records[i].year, &records[i].frequency);
}
And here's the entire program:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
struct nameRecord {
char name[31];
int year;
int frequency;
};
void allCaps(char[]);
int getRawData(FILE*, struct nameRecord[], int);
void setYearTotals(struct nameRecord, int, int);
void setNameYearTotals(char, struct nameRecord, int, int);
void getPerHundredThousand(int, int, double);
void printData(double);
void graphPerHundredThousand(double);
int main(void)
{
int currSizem = 0;
int currSizef = 0;
struct nameRecord *records;
FILE* fp = NULL;
FILE* fp2 = NULL;
char name[31];
printf("Please enter your name: ");
scanf("%30[^\n]", name);
printf("your name is %s\n", name);
//opening both male and female name files and reading them in order to get the total number of records in the array
fp = fopen("malebabynames.csv", "r");
if (fp != NULL) {
printf("file opened\n");
while(3 == fscanf(fp, "%[^,],%d,%d", records[currSizem].name, &records[currSizem].year, &records[currSizem].frequency)) {
currSizem++;
}
} else {
printf("file failed to open\n");
}
if(currSizem > 0) {
records = malloc(currSizem * sizeof(struct nameRecord));
}
fp2 = fopen("femalebabynames.csv", "r");
if (fp != NULL) {
printf("file opened\n");
while(3 == fscanf(fp2, "%[^,],%d,%d", records[currSizef].name, &records[currSizef].year, &records[currSizef].frequency)) {
currSizef++;
}
} else {
printf("file failed to open\n");
}
if(currSizef > 0) {
records = malloc(currSizef * sizeof(struct nameRecord));
}
return 0;
}
//function that automatically capitalizes the users inputted name
void allCaps(char s[]) {
while(*s != '\0') {
*s = toupper((unsigned char) *s);
s++;
}
}
//function that reads and places the read files into the struct arrays
int getRawData(FILE* fp, struct nameRecord records[], int currSize) {
int i;
for(i = 0; i < currSize; i++) {
fscanf(fp, "%[^,],%d,%d", records[i].name, &records[i].year, &records[i].frequency);
}
return 0;
}
approximately as follows :
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
struct nameRecord {
char name[31];
int year;
int frequency;
};
int getRawData(FILE*, struct nameRecord[], int);
int main(void){
const char *MaleFilePath = "malebabynames.csv";
const char *FemaleFilePath = "femalebabynames.csv";
int currSizem = 0;
int currSizef = 0;
FILE* mfp = NULL;
FILE* ffp = NULL;
struct nameRecord *recordsOfMale, *recordsOfFemale;
//opening both male and female name files and reading them in order to get the total number of records in the array
mfp = fopen(MaleFilePath, "r");
if (mfp != NULL) {
int dummy;
printf("file opened\n");
//line count
while(1 == fscanf(mfp, " %*[^,],%*d,%d", &dummy)){
++currSizem;
}
} else {
printf("file(%s) failed to open\n", MaleFilePath);
exit(EXIT_FAILURE);
}
if(currSizem > 0) {
recordsOfMale = malloc(currSizem * sizeof(struct nameRecord));
if(recordsOfMale == NULL){
perror("malloc for Male records");
exit(EXIT_FAILURE);
}
}
rewind(mfp);
if(currSizem != getRawData(mfp, recordsOfMale, currSizem)){
fprintf(stderr, "I could not read a record for the specified number\n"
"at reading %s\n", MaleFilePath);
exit(EXIT_FAILURE);
}
fclose(mfp);
//Do something
free(recordsOfMale);
return 0;
}
//function that reads and places the read files into the struct arrays
int getRawData(FILE* fp, struct nameRecord records[], int currSize) {
int i;
for(i = 0; i < currSize; i++) {
if(3!=fscanf(fp, " %[^,],%d,%d", records[i].name, &records[i].year, &records[i].frequency))
break;
}
return i;
}