Unable to read a structure from a text file in C - c

#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int id;
char* name;
float weight;
} Person;
int main()
{
Person *person=malloc(10*sizeof(Person));
int i=0;
char row[20];
FILE *input=fopen("input.txt","r+");
while(fscanf( input, "%s", &row)>0) i++;
i/=5;
printf("%d\n", i);
fseek(input,0,SEEK_SET);
int j;
char string[20];
for (j=0;j<i;j++){
fscanf(input,"%s",string);
fscanf(input,"ID:%d",&person[j].id);
fscanf(input,"Name:%s",person[j].name);
fscanf(input,"Weight:%f",&person[j].weight);
fscanf(input,"%s",string);
}
fclose(input);
//Person:{
//ID:1214124141
//Name:Trump
//Weight:101.50
//}
//Person:{
//ID:5235252525
//Name:Obama
//Weight:78.30
//}
return 0;
}
Hello!
I want to read a structure from a file, but my array person contains only 0 even after I read from the file. My input file has the structure shown in the comment lines.
What am I not doing well?
Thanks a lot for the help!

fix like this
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
long long int id;//32bit int can't hold like 5235252525
char name[20];//Allocate space
float weight;
} Person;
#define FORMAT "%*s ID:%lld Name:%19[^\n] Weight:%f %*s"
int main(void){
FILE *input=fopen("input.txt", "r+");
if(!input){
perror("fopen");
return -1;
}
int n = 0;
Person p;
while(3==fscanf(input, FORMAT, &p.id, p.name, &p.weight))
++n;
printf("number of record: %d\n", n);
Person *person = malloc(n * sizeof(Person));
if(!person){
perror("malloc");
fclose(input);
return -2;
}
rewind(input);
for (int i = 0; i < n; ++i){
fscanf(input, FORMAT, &person[i].id, person[i].name, &person[i].weight);
}
fclose(input);
//check print
for (int i = 0; i < n; ++i){
printf("ID:%lld, Name:%s, Weight:%.2f\n", person[i].id, person[i].name, person[i].weight);
}
free(person);
return 0;
}

Related

execution problem in read/write from file exercise (newbie)

i wrote a programe to read integers from a .txt file and put them in an array, it compiles just fine ,but would ask for the number of integers then stops
#include <stdlib.h>
#include <stdio.h>
void genererN ( int n){
int i=0;
FILE* fichier = NULL;
fichier=fopen("valeurs.txt","w");
while (i<n){
fprintf(fichier,"\n%d\n",rand());
i++;
}
}
void replirtab (int **t,int n){
int i=0;int m;
FILE* fichier = NULL;
fichier=fopen("valeurs.txt","r");
char stre[999999] = "";
while(i<n){
fgets(stre, 999999, fichier);
m = atoi(stre);
*t[i]=m;
i++;
}
}
void affichertab (int *t,int n){
int i=0;
while(i<n){
printf("%d\n",t[i]);
i++;
}
}
and this is my main function where i ask for the number of randomly generated integers and use my functions
#include <stdio.h>
#include <stdlib.h>
#include "source1.h"
int main()
{
int n;
printf("donner le nombre de valeurs ");
scanf("%d",&n);
int T[n];
genererN(n);
replirtab(T,n);
affichertab(T,n);
return 0;
}
and the header
#ifndef SOURCE1_H_INCLUDED
#define SOURCE1_H_INCLUDED
void genererN ( int n);
void replirtab (int *t,int n);
void affichertab (int *t,int n);
#endif // SOURCE1_H_INCLUDED
Fix the following problems:
You're not closing the file after you write it, so the buffer isn't being flushed.
You're writing an extra newline before each number, but you don't skip it when reading.
replirtab() expects an array of pointers, but the array contains integers, not pointers. There's no need to indirect through the references. When you pass an array to a function, a pointer to the first element is passed.
#include <stdlib.h>
#include <stdio.h>
void genererN ( int n){
int i=0;
FILE* fichier = NULL;
fichier=fopen("valeurs.txt","w");
if (!fichier) {
printf("Unable to write file\n");
exit(1);
}
while (i<n){
fprintf(fichier,"%d\n",rand());
i++;
}
fclose(fichier);
}
void replirtab (int *t,int n){
int i=0;int m;
FILE* fichier = NULL;
fichier=fopen("valeurs.txt","r");
if (!fichier) {
printf("Unable to read file\n");
exit(1);
}
char stre[999999] = "";
while(i<n){
fgets(stre, 999999, fichier);
m = atoi(stre);
t[i]=m;
i++;
}
fclose(fichier);
}
void affichertab (int *t,int n){
int i=0;
while(i<n){
printf("%d\n",t[i]);
i++;
}
}

Seg Fault occurs while malloc-ing

This function is a part of program which will gain statistics about books (amount of specific letters, words etc.). Thing is that segmentation fault appears when trying to malloc:
*wordArray[arrayIndex] = malloc(sizeof(***wordArray)*(wcslen(newWord)+1));
after reallocing whole array
*wordArray = realloc(*wordArray, (arrayIndex+1)*sizeof(**wordArray));
I know that realloc isn't really efficent but the most important thing at the moment is to understand why it doesn't work at all. Thanks a lot.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
#include <wctype.h>
#include <wchar.h>
#define X 2
void wordManager(wchar_t ***, int **, wchar_t *);
int main(int argc, char **argv){
setlocale(LC_ALL, "");
wchar_t **wordArray;
int *wordAmount;
wchar_t word[50];
for(int i=0; i<X; i++){
scanf("%ls", word);
wordManager(&wordArray, &wordAmount, word);
}
for(int i=0; i<X; i++){
printf("%ls; %d times\n", wordArray[i], wordAmount[i]);
}
}
void wordManager(wchar_t ***wordArray, int **wordAmount, wchar_t *newWord){
static int isArrayInitialised = 0;
static int isArrayEmpty = 1;
static int arrayIndex = 0;
int wordLocation;
if(!isArrayInitialised){
*wordArray = malloc(sizeof(**wordArray)*1);
if(*wordArray==NULL){
printf("Error mallocing wordArray");
exit(EXIT_FAILURE);
}
*wordAmount = calloc(1, sizeof(*wordAmount));
if(*wordAmount==NULL){
printf("Error callocing wordAmount");
exit(EXIT_FAILURE);
}
isArrayInitialised = 1;
}
if(isArrayEmpty){
*wordArray[0] = malloc(sizeof(***wordArray)*(wcslen(newWord)+1));
wcscpy(*wordArray[0], newWord);
*wordAmount[0] = 1;
isArrayEmpty = 0;
}
else{
//Check if word is already in an array.
wordLocation = 0;
for(; wordLocation<arrayIndex+1; wordLocation++){
if(!wcscmp(*wordArray[wordLocation], newWord)) break;
}
printf("%d\n", wordLocation);
//Word hasn't been found. Then:
if(wordLocation==arrayIndex+1){
arrayIndex++; //Increase arrays' volume.
*wordArray = realloc(*wordArray, (arrayIndex+1)*sizeof(**wordArray));
if(*wordArray==NULL){
printf("Error reallocating wordArray memory.\n Array index: %d", arrayIndex);
exit(EXIT_FAILURE);
}
*wordAmount = realloc(*wordAmount, (arrayIndex+1)*sizeof(**wordAmount));
if(*wordAmount==NULL){
printf("Error reallocating wordAmount memory.\n Array index: %d", arrayIndex);
exit(EXIT_FAILURE);
}
*wordArray[arrayIndex] = malloc(sizeof(***wordArray)*(wcslen(newWord)+1));
wcscpy(*wordArray[arrayIndex], newWord);
*wordAmount[arrayIndex] = 1;
}
//Word has been found in an array.
else{
(*wordAmount[wordLocation])++;
}
}
}

Segmentation error 11 when using struct arrays in c

I am working on a project and have hit a snag that I have spent hours trying to figure out. I'm fairly certain its very close to correct but obviously something is wrong in my malloc of the struct array. I'll post the code below so you can see it. The goal of this function set is to read in movie data saved in a file and put the data into a structure.
#include <stdio.h>
#include <stdlib.h>
#include "support.h"
#include "scanner.h"
#include <string.h>
int counter(char *movierecords)
{
int count = 0;
char *name;
char *about;
int date;
int time;
char *rate;
char *ppl;
char *dir;
//printf("test");
FILE *fp = fopen(movierecords, "r");
//printf("gggg");
name = readString(fp);
while (!feof(fp))
{
//printf("test in loop");
about = readString(fp);
date = readInt(fp);
time = readInt(fp);
rate = readToken(fp);
ppl = readString(fp);
dir = readString(fp);
//printf("test read");
free(name);
free(about);
free(rate);
free(ppl);
free(dir);
//printf("test free");
count++;
name = readString(fp);
}
//printf("test escape loop");
fclose(fp);
//printf("test file close");
return count;
}
movie **readRecord(char *movierecords, int count) //mallocates space and reads data into an array of movie structures
{
int x = 0;
movie **data1;
FILE *fp = fopen(movierecords, "r");
data1 = malloc(sizeof(struct movie *) * (count + 1)); //mallocate space for the struct array movies1
printf("another test");
while (x < count + 1) //loop mallocates space for the string variables in movies1 struct for all movies
{
data1[x]->moviename = malloc(sizeof(char) * 1001);
data1[x]->description = malloc(sizeof(char) * 2001);
data1[x]->rating = malloc(sizeof(char) * 10);
data1[x]->cast = malloc(sizeof(char) * 512);
data1[x]->director = malloc(sizeof(char) * 30);
x++;
}
printf("test point3\n"); x = 0;
while (!feof(fp))
{
data1[x]->moviename = readString(fp);
data1[x]->description = readString(fp);
data1[x]->year = readInt(fp);
data1[x]->length = readInt(fp);
data1[x]->rating = readToken(fp);
data1[x]->cast = readString(fp);
data1[x]->director = readString(fp);
x++;
}
printf("test point4\n");
fclose(fp);
return data1;
}
Header file:
typedef struct entry
{
char *moviename;
char *description;
int year;
int length;
char *rating;
char *cast;
char *director;
} movie;
int counter(char *movierecords);
movie **readRecord(char *movierecords, int count);
Main:
#include <stdio.h>
#include <stdlib.h>
#include "support.h"
#include <string.h>
int main (int argc, char **argv)
{
int count = 0;
printf("%d", argc);
movie **data1;
count = counter(argv[1]);
printf("%d", count);
printf("hello");
data1 = readRecord(argv[1], count);
return 0;
}
You have to allocate memory for this "data1[x]" because your malloc(double pointer) allocate memory for array of your records(single pointer). Fot the single pointer data[x] you have to allocate memory

getting fscanf to store in structs in C

I have an assignment where I need to get Values of RLC circuits from a file and calculate the resonant frequency however my issue is when I use the fscanf function it reads only the first line of the file and the rest comes out as zeros .
#include <stdio.h>
data
int h;
typedef struct cct
{
int code[50];
float R[50];
float L[50];
float C[50];
} CCT;
int read(CCT cct[], int n_p, FILE* fp){
char temp;
if(fp==NULL){
printf("Error\n");
return -1;
}
fscanf(fp,"%d,%f,%e,%e\n", cct[n_p].code, cct[n_p].R,cct[n_p].L, &cct[n_p].C);
}
int main()
{
FILE* fp = fopen("U://datafile.txt", "rt");
int i = 0;
CCT cct[50];
int size;
while (!feof(fp)) {
read(cct, i, fp);
i++;
}
size = i;
for (i = 0; i < size; ++i)
printf("%d,%0.2f,%0.2f,%0.2f\n", cct[i].code[i], cct[i].R[i],
cct[i].L[i], cct[i].C[i]);
scanf("%d",&h);
fclose(fp);
}
and this is the data file
1,4.36,2.23e-2,4.65e-8
2,4.57,2.01e-2,5.00e-8
3,3.99,2.46e-2,4.82e-8
4,4.09,2.60e-2,4.70e-8
I would appreciate if someone could point put why it only gets the first line. Thanks
CCT is composed of multiple arrays (you have arrays of arrays, which is wrong for the exercise, but that's not the point) and you always write to the element zero of the arrays. For example, cct[n_p].code in fscanf() is the address of the array, which is identical to the address of cct[n_p].code[0]. Then you print code[i] in the output loop, which is blank except for i == 0.
fscanf(fp,"%d,%f,%e,%e", cct[n_p].code, cct[n_p].R,cct[n_p].L, cct[n_p].C);
...
printf("%d,%0.2f,%0.2f,%0.2f\n", cct[i].code[0], cct[i].R[0], cct[i].L[0], cct[i].C[0]);
Something like the following, perhaps
#include <stdio.h>
typedef struct cct {
int code;
float R;
float L;
float C;
} CCT;
int h;
int read(CCT cct[], int n_p, FILE* fp){
char temp;
if(fp==NULL){
printf("Error\n");
return -1;
}
fscanf(fp,"%d,%f,%e,%e\n", &cct[n_p].code, &cct[n_p].R, &cct[n_p].L, &cct[n_p].C);
}
int main(){
FILE* fp = fopen("U://datafile.txt", "rt");
int i = 0;
CCT cct[50];
int size;
while (!feof(fp)) {
read(cct, i, fp);
i++;
}
size = i;
for (i = 0; i < size; ++i)
printf("%d,%0.2f,%0.2f,%0.2f\n", cct[i].code, cct[i].R, cct[i].L, cct[i].C);
scanf("%d",&h);
fclose(fp);
}

Using a char array as input to module to scan a file in C

I am trying to use the getStats function twice - once for each input file. I am supposed to be using a char array called statFile[]to pass as the argument to the prototype to select which file it is to work with. Currently I know how to use one file at a time (by explicit naming the file in the prototype) to make it work, but do not understand how to use it for both inputs. Thanks in advance!
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define AUBURN "auburn2013.txt" //input data files
#define ALABAMA "alabama2013.txt" //input data files
#define NUMGAMES 13
int getStats( char statFile[], int compPass[], int attPass[], int numYds[], int numTD[] );
void analysis( int compPass[], int attPass[], int numYds[], int numTD[], double aveYds[], double pectCmp[], int tdPts[], int numGames[]);
int main(void)
{
int compPass[NUMGAMES],
attPass[NUMGAMES],
numYds[NUMGAMES],
numTD[NUMGAMES];
double bamaStats,
auburnStats,
setAuburn,
setBama;
FILE *au = fopen("auburn2013.txt","r");
FILE *al = fopen("alabama2013.txt","r");
if (al == NULL)
printf("Error Opening File\n");
else if (au == NULL)
printf("Error Opening File\n");
bamaStats = getStats(ALABAMA, compPass, attPass, numYds, numTD);
return 0;
}
int getStats( char statFile[], int compPass[], int attPass[], int numYds[], int numTD[] )
{
int i,
p,
k = sizeof(compPass[NUMGAMES]);
FILE *al = fopen("alabama2013.txt","r");
while (fscanf(al ,"%d %d %d %d", &compPass[i], &attPass[i], &numYds[i], &numTD[i]) !=EOF)
{
i++;
}
printf("Number of Games with data: %d\n", i);
for(p=0; p<8 ; p++)
{
printf("%d %d %d %d\n", compPass[p], attPass[p], numYds[p], numTD[p]);
}
return 0;
}
You are already passing in the stat file name, so need to change:
FILE *al = fopen("alabama2013.txt","r");
to
FILE *al = fopen(statFile,"r");
You can do that like this:
#include <stdio.h>
#include <assert.h>
void print_fname(char **farray, int fnum)
{
int i;
assert(farray != NULL);
for (i = 0; i < fnum; ++i) {
assert(farray[i] != NULL);
printf("file name %d: %s\n", i + 1, farray[i]);
}
}
int main()
{
char *farray[] = {"file1", "file2"};
print_fname(farray, 2);
return 0;
}
Hope can help.

Resources