What is wrong with a program? - c

Programm crushes, help me please, thanks in advance. The file can be downloaded below.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int deed_id;
char deed_name[55];
int points_for_deed;
int total_times_done;
int total_points_earned;
} deed;
int main(){
FILE *file1;
file1=fopen("deed_list.txt", "r");
if(file1==NULL){
printf("Can not open the file");
return 1;
}
int j;
fscanf(file1, "%i", &j);
deed **deed_list = (deed**)malloc(sizeof(deed)*j);
int i;
for(i=0; i<j; i++){
fscanf(file1, "%i %s %i", &deed_list[i]->deed_id, deed_list[i]->deed_name, &deed_list[i]->points_for_deed);
}
printf("%i",j);
fclose(file1);
return 0;
}
https://sst-csci.com/csci151/wp-content/uploads/deed_list.txt

deed **deed_list = (deed**)malloc(sizeof(deed)*j);
You don't want a pointer to pointer to store an array of deed, change to a single pointer (and don't cast malloc):
deed *deed_list = malloc(sizeof(deed)*j);
Don't forget to call free(deed_list); at the end.

Related

C - Reading strings from text file into arrays inside a structure

I am trying to read text from a .txt file into arrays of a structure.
This is my code (I have played around with this a heap so apologies if it seems all over the place):
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <stdbool.h>
#include <time.h>
#include <string.h>
#include <ctype.h>
int main()
{
int i = 1;
int j = 0;
char temp[4];
struct userStruct { // a struct definition for the users;
char pin[5];
char first[26];
char last[26];
};
struct userStruct userList[10]; // an array of struct user to hold 10 users
struct userStruct * users;
users = &userList;
FILE * filePtr;
filePtr = fopen ("users.txt", "r");
if (filePtr != NULL)
{
fscanf(filePtr, "%s %s %s %s", users[i].pin[j], users[i].first[j], users[i].last[j], temp);
if (strcmp(temp, "\n"))
{
i++;
j++;
}
printf("PIN %s| First %s| Last %s|", users[i].pin[j], users[i].first[j], users[i].last[j]);
fclose(filePtr);
}
else
{
printf("Unable to open users.txt");
}
return 0;
}
The users.txt file contains the text:
1234 John Smith
5678 Barry Cool
Many thanks for the help.
You only want 3 conversion specifiers in the scanf. Try
if( 3 == fscanf(filePtr, "%4s %25s %25s", users[i].pin, users[i].first, users[i].last) ){ ...
The printf is also weird. Try:
printf("PIN %s| First %s| Last %s|", users[i].pin, users[i].first, users[i].last);

Storing values from a file into an array with malloc

for an assignment I am meant to store values from a file into an array using malloc. The code compiles but stays stuck in the terminal when I execute it. I thought that i was not storing the value from the file but that is working fine. I think I'm using the array incorrectly.
Thank you.
#include <stdio.h>
#include <stdlib.h>
int main(void){
double* arrayPtr = malloc( 10* sizeof(double));
char lines[128]; //the lines of the txt file
int i;
FILE* file;
file = fopen("TriData1.txt", "r");
int count = 0;
while (fgets(lines, 128, file))
{
scanf(lines, "%d", &i);
scanf(" %le", &arrayPtr[i]);
printf(" %d\n", i);
printf("line %d: %f\n", (count + 1), arrayPtr[count])
count++;
}
free(arrayPtr);
return 0;
}

Can't Solve Segfault Error

This isn't all of the program, but it doesn't run past this function. It seems to have the segfault near the fscanf statement, but I don't think that's what's causing the error. I really don't see anything that could cause the segfault error, but I'm an amateur and probably missed something. All of the printf statements are for debugging purposes.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#define N 10
struct point2d_def
{
int x;
int y;
};
typedef struct point2d_def point2d;
void fill(char str[], point2d P[])
{
FILE *ifp = NULL;
ifp = fopen(str, "r");
int i = 0;
if (ifp == NULL)
{
printf("Could not open %s for reading\n", ifp);
exit(1);
}
for(i = 0; i < N; ++i)
{
fscanf(ifp, "%d %d", &P[i].x, &P[i].y);
}
fclose(ifp);
printf("Fill function passed\n");
return;
printf("Blorp");
}
first you are declaring P[N] inside the func, and receiving P in the parameters.
second, you are writing to 11 slots instead of 10:
for(i = 0; i < N; ++i){
fscanf(ifp, "%d %d", &P[i].x, &P[i].y);
}
remove the =...

Storing .txt file into structures

I'm trying to store the .txt file into struct, not being successful.
I dont need the first line stored, but I do need the rest.
Thanks guys !! =)
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
int main(int argc, const char * argv[]) {
// insert code here...
printf("Hello, World!\n");
struct candidates
{
char name[25];
char gender[5];
int height;
int weight;
};
struct candidates values[25];
FILE *fp;
if ((fp=fopen("candidatesdata.txt","r"))==NULL){printf("Unable to open file\n");}
int x = 0;
int iterations = 0;
while((fscanf(fp,"%s,%s,%d,%d",&values[x].name, &values[x].gender, &values[x].height, &values[x].weight))!=EOF)
{
x++;
iterations +=1;
}
fclose(fp);
//values[15].weight = 300;
printf("\n%d\t%d",iterations,values[1].height);
return 0;
}
Text file looks like the following:
Name,Gender,Height,Weight
Tanner,M,71.8,180.25
John,M,70.75,185.3
Parker,F,65.25,120.3
Meeks,M,57.25,210.2
struct candidates
{
char name[25];
char gender[5]; // can be char gender too !!
int height; // should be changed to float height
int weight; // should be changed to float height
};
If you actually have :
Name,Gender,Height,Weight
in your file, you might do his before you go to the while loop :
char somebigstring[100];
.
.
.
if(fscanf(fp,"%s",somebigstring) == EOF) //wasting the first line
exit(-1); // exiting here if there is no first line
fix like this:
#include <stdio.h>
#include <stdlib.h>
struct candidates{
char name[25];
char gender[7];//Female+1
float height;
float weight;
};
int main(void) {
struct candidates values[25];
FILE *fp;
if ((fp=fopen("candidatesdata.txt","r"))==NULL){
fprintf(stderr, "Unable to open file\n");
exit(EXIT_FAILURE);
}
char line[64];
int x = 0;
int iterations = 0;
while(fgets(line, sizeof line, fp)){
iterations += 1;
if(x < 25 && sscanf(line, "%24[^,],%6[^,],%f,%f", values[x].name, values[x].gender, &values[x].height, &values[x].weight)==4){
x++;
} else if(iterations != 1){
fprintf(stderr, "invalid data in %d line: %s", iterations, line);
}
}
fclose(fp);
for(int i = 0; i < x; ++i){
printf("%s,%c,%.2f,%.2f\n", values[i].name, *values[i].gender, values[i].height, values[i].weight);
}
return 0;
}
This code does two following things; first is writes data into .txt file and the second it reads data from .txt file and stores in struct data type which is what you are trying achieve but only for single entity. Next you should implement this as for entities.
#include<stdio.h>
#include<stdlib.h>
typedef struct{
char name[30];
//other fields
}Candidate;
typedef struct{
Candidate c;
char city[30];
int vote;
}CityVotes;
//for .bin operations
void write_to_file(FILE *f)
{
Candidate c;
CityVotes cv;
printf("Enter candidate name : ");
scanf("%s",&c.name);
cv.c = c;
printf("Enter the city : ");
scanf("%s",&cv.city);
printf("Enter the vote : ");
scanf("%d",&cv.vote);
fwrite(&cv, sizeof(cv), 1, f);
}
//for .txt operations
void write_to_file1(FILE *f)
{
Candidate c;
CityVotes cv;
printf("Enter candidate name : ");
scanf("%s",c.name);
cv.c = c;
printf("Enter the city : ");
scanf("%s",&cv.city);
printf("Enter the vote : ");
scanf("%d",&cv.vote);
fprintf(f,"%s ", cv.c.name);
fprintf(f,"%s ", cv.city);
fprintf(f,"%d ", cv.vote);
}
//for .bin operations
void read_file(FILE *f)
{
CityVotes cv;
while(fread(&cv, sizeof(cv), 1, f)){
printf("Candidate : %s\t",cv.c.name);
printf("City.: %s\t",cv.city);
printf("Vote.: %d\n",cv.vote);
}
}
//for .txt operations
void read_file1(FILE *f){
CityVotes cv;
fscanf(f," %s", &cv.c.name);
fscanf(f," %s", &cv.city);
fscanf(f," %d", &cv.vote);
printf("Candidate : %s\t",cv.c.name);
printf("City.: %s\t",cv.city);
printf("Vote.: %d\n",cv.vote);
}
int main(void)
{
FILE *f;
f=fopen("candidates.txt","w");
write_to_file1(f);
fclose(f);
f=fopen("candidates.txt","r");
read_file1(f);
return 0;
}
Be aware, the code just is example , you should check for nulls.

Ragged Arrays and For Loop errors

I get a bad access error in the middle of the for loop, always when i=4. Does anybody know the reason for this? It works until i=4, but I don't see why I wouldn't get the bad access error in any other part of the for loop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAXF 51
#define MAXFILE 200
int recommend(int fid, char *funcs[]){
int i;
for(i=0; i<fid; i++)
*funcs++;
printf("\nRecommended Function: %s\n", *funcs);
return 0;
}
int overlap(char *list[], char name[], int n){
int over=0, fid=202, i, j, k, m;
for(i=0; i<n; i++){
m=strlen(*list);
int lap=0;
for(j=0; j<(strlen(name)-1); j++){
for(k=0; k<m; k++)
if(list[i][k]==name[j]){
lap+=1;
break;
}
}
if(over<lap){
over=lap;
fid=i;
}
*list++;
}
return fid;
}
int readfile(char *flist[], FILE *fptr){
char a[MAXF];
int size=0;
while(fscanf(fptr, "%s\n", a) != EOF){
flist[size]=malloc(sizeof(char)*(1+strlen(a)));
strcpy(flist[size++],a);
}
return size;
}
int main () {
int n, id;
char fnname[MAXF], filename[MAXF], *flist[MAXFILE];
FILE *fp;
printf("Name of network file: ");
gets(filename);
printf("\nFunction Name: ");
gets(fnname);
fp=fopen(filename, "r");
if(fp==NULL)
printf("\nCould not open file.\n");
else {
n=readfile(flist, fp);
id=overlap(flist, fnname, n);
recommend(id, flist);
}
return 0;
}
It looks to me as if this:
m=strlen(*list);
should be:
m=strlen(list[i]);
And this:
*list++;
should not be there at all.

Resources