passing struct in function - c

I spend lot of time to pass a struct pointer in a function. everything in the code is working only I couldn't figure out how to pass a struct in a function then I can do some operation inside a function. can you explain where exactly i'm fail and how to fix it? Thanks.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int i=0;
int* i_ptr=&i;
int count(int q);
int line_count();
struct student {
int st_id;
char st_name[20];
int st_age;
char st_dep[7];
float st_grade;
};
int sort_student(struct student line[i],int i)
{
printf("%f",line[1].st_grade);
printf(" %s",line[1].st_name);
return 0;
}
int main()
{
/* struct loading from the file operation goes here */
int x=0;
int i=line_count();
struct student line[i];
char file_line[100];
char* line_parts;
FILE * fp;
if ((fp = fopen (file.txt", "r")) != NULL)
{
while (x<i) {
if(fgets(file_line,100,fp) != NULL); // gets line from the file.
{
line_parts = strtok(file_line,","); // breaks the line
line[x].st_id = atoi(line_parts); // conversition string to int
line_parts = strtok(NULL, ",");
strcpy(line[x].st_name,line_parts);
line_parts = strtok(NULL, ",");
line[x].st_age = atoi(line_parts);
line_parts = strtok(NULL, ",");
strcpy(line[x].st_dep,line_parts);
line_parts = strtok(NULL, ",");
line[x].st_grade = atoi(line_parts);
x++;
}
}
}
fclose(fp);
sort_student(&line[i],i);
return 0;
}
int line_count () //counts the number of line in the file, while loading the program.
{
FILE * fp; // file open from here.
int i=0;
int c;
if ((fp = fopen ("/Users/rishav/Desktop/try/try/file.txt", "r")) != NULL)
{
while ((c=fgetc(fp)) != EOF) {
if (c=='\n') {
i++;
}
}
fclose(fp);
}
else printf("file reading Error.\n");
return i;
}
int count(q) // keeps track of i
{
if(q==1)
{
(*i_ptr)++;
}
return *i_ptr;
}

You need to change your sort_student function definition to
int sort_student(struct student* line,int i) {
printf("%f",line->st_grade);
printf(" %s",line->st_name);
return 0;
}

Related

warning: passing argument 1 of 'gets' from incompatible pointer type

gets() function takes one argument and this is a FILE-type. That's happening in my code but It doesn't work. I'm trying to get every single symbol from the file with a cycle like it happened in docs. What's the problem?
The error happens in the 'load' function. String: "while ((symbol = gets(file)) != EOF)"
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
char name[20];
int age;
} person;
void save(char way[100], person *object);
void load(char way[100]);
FILE *file;
int main(void)
{
char way[100] = "D:\\Projects\\C\\C06_WorkingWithFiles\\C004_ReadingAndWritingStructures.dat";
person object = {"Tom", 15};
person *p_object = &object;
save(way, p_object);
load(way);
fclose(file);
return 0;
}
void save(char way[100], person *object)
{
if (fopen(way, "r") == NULL)
{
file = fopen(way, "w");
}
char *c = (char *)object;
for (int i = 0; i < sizeof(person); i++)
{
putc(*c, file);
c++;
}
}
void load(char way[100])
{
if ((file = fopen(way, "r")) == NULL)
{
perror("\nError");
exit(0);
}
person object, *p_object = &object;
char symbol, *c = (char *)p_object;
while ((symbol = gets(file)) != EOF)
{
*c = symbol;
c++;
}
printf("\nName: %s | Age: %d\n", p_object -> name, p_object -> age);
}
i had to write 'getc' instead of 'gets' like this:
while ((symbol = getc(file)) != EOF)

INI file reader function is addressing wrong values to my structure, How do I solve this?

This is for a project for university (small replica of a Catan game) and I'm struggling a bit with this part, we have the read an INI file with fairly simple formatting, it only has some comments starting with ';' and then it's just tags with a value in front:
xdim=4
ydim=5
N=D
S=L2
E=S10
W=D
etc...
I have this function to read from an INI file and address the read values to the correct struct element. But it seems like it doesn't even read the file, the struct is a simple struct with xdim and ydim, after I call the func xdim is '&d&d&d&d etc...' and ydim is 0
I've tried placing in some printf's just to see if the values from the INI file itself where being read wrong, but nothing is printed.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 128
typedef struct UNIT { /**struct used in an array for the rest of the INI values*/
char N[4];
char S[4];
char W[4];
char E[4];
char Building;
}UNIT;
typedef struct{ /**This is declared in main and passed to the functions*/
UNIT *grid;
unsigned int xdim;
unsigned int ydim;
} MAP_CONFIG;
void set_config_val(MAP_CONFIG *config, const char *key, int val) {
if (config == NULL)
return;
if (strcmp(key, "xdim") == 0){
printf("here");
config->xdim = val;
}
else if (strcmp(key, "ydim") == 0){
printf("here");
config->ydim = val;
}
else{
;
}
}
void read_config(MAP_CONFIG *config,FILE *f) {
char str[MAX];
char *token;
const char *delim = "=\n";
while (1) {
fgets(str, MAX, f);
if(feof(f)!= 0) break;
puts(str);
if (strchr(str, '=')!=NULL) {
char varname[MAX];
int value;
token = strtok(str, delim);
strcpy(varname, token);
token = strtok(NULL, delim);
value = atoi(token);
printf("&d", token);
set_config_val(config, varname, value);
}
}
config = malloc(sizeof(MAP_CONFIG));
config->grid = calloc(config->xdim * config->ydim, sizeof(UNIT));
close(f);
return;
}
open file function:
FILE *openFile(char *nome, char *mode) {
FILE *f;
printf("Opening file %s\n", nome);
f = fopen(nome, mode);
if (f == NULL) {
fprintf(stderr, "*** It was not possible to open the file %s.", nome);
exit(1);
}
return f;
}
test main im using:
int main(int argc, char **argv) {
MAP_CONFIG map;
MAP_CONFIG *mapa = &map;
FILE *f;
char *filename;
for (int i = 0; i < argc; i++)
printf("Parametro %d: %s\n", i, argv[i]);
if (argc >= 2) {
filename = argv[1];
}
else {
printf("Opening base map file..\n");
filename = "mapa.ini";
}
f = openFile(filename, "r");
read_config(mapa, f);
printf("%d %d", map.xdim, map.ydim);
return 0;
}
I just want it to read the xdim and ydim, and then repeat the process to an array of structs for each struct to get the correct value of the N,S,E,W present in the INI file... Help!

C Programming: Reading a file and storing in array of struct

I am trying to read a file test.txt via fscanf and store it in a array of struct. This is what I tried. Problem here is that fscanf is not working as it is supposed to. After reading the file, I am also trying to print it on screen, but it won't work.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Item {
double value;
int unit;
char name[50];
};
int load(struct Item* item, FILE* data);
void display(struct Item item, int variableA);
int main()
{
struct Item I;
int i;
char ck;
ck = fopen("test.txt", "r");
if (ck)
{
for (i = 0; i < 3; i++)
{
load(&I, ck);
display(I, 0); //DISPLAY FUNCTION THAT READS test.txt and DISPLAYS
}
fclose(ck);
}
return 0;
}
int load(struct Item* item, FILE* data)
{
fscanf(data, "%d,%.2lf,%s\n", &(*item).unit,&(*item).value,&(*item).name);
return 0;
}
void display(struct Item item, int variableA)
{
printf("|%3d |%12.2lf| %20s |***\n", item.unit, item.value, item.name);
return;
}
This is what I have in test.txt file:
205,11.20,John Snow
336,23.40,Winter is coming
220,34.20,You know nothing
Error: Program compiles with some warnings , but I get segmentation fault when I execute the code.
Any idea why?
Output Expectation: OUTPUT should be read from test.txt file and should be displayed on to the screen.
Multiple problems in the program:
1.
char ck;
ck = fopen("test.txt", "r");
fopen returns a FILE*, not a char, use
FILE* ck = fopen(...);
2.
fscanf(data, "%d,%.2lf,%s\n", &(*item).unit,&(*item).value,&(*item).name);
always check return value of fscanf, if it is smaller than the number of fields you requested, the following call to fscanf is unlikely to do what you expect. Also, *item.unit is the same as item->unit, use item->unit because it is shorter and cleaner:
int ret = fscanf(data, "%d,%lf,", &item->unit, &item->value);
if (ret != 3) { // error }
Third, %s matches a sequence of non-white-space characters, so when fscanf reads "John", it will stop, and the next fscanf call will get to read "Snow" while expecting an integer.
So to input a string with whitespace, use fgets instead, and remember to remove the newline character in the end.
Try following:
int main(void)
{
struct Item I;
int i;
FILE* ck;
int ret;
ck = fopen("test.txt", "r");
if (ck)
{
for (i = 0; i < 3; i++)
{
ret = load(&I, ck);
if (ret < 0)
break;
display(I, 0); //DISPLAY FUNCTION THAT READS test.txt and DISPLAYS
}
fclose(ck);
}
return 0;
}
int load(struct Item* item, FILE* data)
{
int ret = fscanf(data, "%d,%lf,", &item->unit, &item->value);
if (ret != 2) {
return -1;
}
fgets(item->name, sizeof item->name, data);
item->name[strlen(item->name)-1] = '\0';
return 0;
}
void display(struct Item item, int variableA)
{
printf("|%3d |%12.2lf| %20s |***\n", item.unit, item.value, item.name);
return;
}
It outputs:
$ ./a.out
|205 | 11.20| John Snow |***
|336 | 23.40| Winter is coming |***
|220 | 34.20| You know nothing |***
You can try this different approach.
It uses:
malloc,realloc to allocate and reallocate memory for array of structs. I assumed that much larger text files with more lines will be used and this allows the array to resize when needed to accommodate more information.
strtok to parse each peice of data between , delimeters, and then store them into the array of structures.
Checks return value of pointers to avoid segmentation faults.
Uses fgets to read each line of the file into a string, from which we can parse ourselves afterwards.
This is the proposed code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NAMESTRLEN 50
#define INITSIZE 3
#define MAXSIZE 100
typedef struct {
int unit;
double value;
char name[NAMESTRLEN+1];
} item_t;
typedef struct {
item_t *items;
int numlines;
} allitems_t;
allitems_t *initialize_arraystructs(void);
void print_arraystructs(allitems_t *allitems);
void read_insert_items(FILE *filestream, allitems_t *allitems);
void check_ptr(void *ptr, const char *msg);
int
main(void) {
allitems_t *allitems;
FILE *fp;
fp = fopen("test.txt", "r");
if (fp == NULL) {
fprintf(stderr, "%s\n", "Error reading file!\n");
exit(EXIT_FAILURE);
}
allitems = initialize_arraystructs();
read_insert_items(fp, allitems);
print_arraystructs(allitems);
return 0;
}
void
read_insert_items(FILE *filestream, allitems_t *allitems) {
int count = 0;
char line[MAXSIZE];
char *unit, *value, *name;
size_t numitems = INITSIZE;
allitems->items = malloc(numitems * sizeof(item_t));
check_ptr(allitems->items, "Initial Allocation");
while (fgets(line, MAXSIZE, filestream) != NULL) {
unit = strtok(line, ",");
value = strtok(NULL, ",");
name = strtok(NULL, "\n");
if (count == numitems) {
numitems *= 2;
allitems->items = realloc(allitems->items, numitems * sizeof(item_t));
check_ptr(allitems->items, "Reallocation");
}
allitems->items[count].unit = atoi(unit);
allitems->items[count].value = atof(value);
strcpy(allitems->items[count].name, name);
count++;
allitems->numlines++;
}
}
allitems_t
*initialize_arraystructs(void) {
allitems_t *allitems;
allitems = malloc(sizeof(allitems_t));
check_ptr(allitems, "Initial Allocation");
allitems->items = NULL;
allitems->numlines = 0;
return allitems;
}
void
print_arraystructs(allitems_t *allitems) {
int i;
for (i = 0; i < allitems->numlines; i++) {
printf("%d,%.2f,%s\n",
allitems->items[i].unit,
allitems->items[i].value,
allitems->items[i].name);
}
}
void
check_ptr(void *ptr, const char *msg) {
if (!ptr) {
printf("Unexpected null pointer: %s\n", msg);
exit(EXIT_FAILURE);
}
}

Segmentation fault (code dumped) error in C

I was trying to run this code and it is saying "Segmentation fault (code dumped)" how I can fix my code to make this error go away. here is my code so if someone could help me out that would be awesome! How can i fix my void SEARCH
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct _data {
char *name;
long number;
};
int SCAN(FILE *(*stream)){
int count = 0;
char line[256];
while (fgets(line, sizeof(line), *stream)) {
count++;
}
return count;
}
struct _data* BlackBoxLOAD(FILE **stream, int size){
struct _data* BlackBox = (struct _data*)malloc(sizeof(struct _data)*size);
int count = 0;
char line[256];
while (fgets(line, sizeof(line), *stream)) {
char* token = strtok(line, " ");
struct _data* temp = (struct _data*)malloc(sizeof(struct _data));
temp->name = token;
token = strtok(NULL, " ");
temp->number = atoi(token);
BlackBox[count] = *temp;
count++;
}
return BlackBox;
}
void SEARCH(struct _data *BlackBox, char *string, int size){
int i = 0;
for (i = 0; i<size; i++){
if (strcmp(BlackBox[i].name, string) == 0)
return i;
}
return -1;
}
void FREE(struct _data *BlackBox, int size){
free(BlackBox);
return;
}
int main(int argc, char **argv) {
int i = 0, size = 0;
FILE *stream = fopen("hw5.data", "r");
int noOfLines = SCAN(&stream);
size = noOfLines;
struct _data *BlackBox = BlackBoxLOAD(&stream, size);
fclose(stream);
for (i = 1; i<argc; i++){
if (argv[i] == "") {
printf("*******************************************");
printf("* You must include a name to search for. *");
printf("*******************************************");
}
int pos = SEARCH(BlackBox, argv[i], size);
if (pos == -1) {
printf("*******************************************");
printf("The name was NOT found.");
printf("*******************************************");
}
else{
printf("*******************************************");
printf("The name was found at the %d entry.", pos);
printf("*******************************************");
}
}
FREE(BlackBox, size);
}
There are just way too many bugs in this code, but here's the most obvious:
char* token = strtok(line, " ");
struct _data* temp = (struct _data*)malloc(sizeof(struct _data)*1000);
temp->name = token;
You're setting temp->name to the value of token. But token points into line, which is getting modified and will soon cease to exist because you created it on a stack that's about to go away.
You can't save a pointer to a chunk of memory that you're about to reuse.
After the following line has been executed
int noOfLines = SCAN(&stream);
stream is at the end of the file. You need to rewind it before you can read the data. Add the line:
frewind(stream);
after the call to SCAN.
As an aside, you should change the argument type of SCAN and BlackBoxLOAD to FILE*.
int SCAN(FILE *stream){
struct _data* BlackBoxLOAD(FILE *stream, int size){
That will make the calls easier and the functions don't have to dereference stream.
Function definition:
int SCAN(FILE *stream){
int count = 0;
char line[256];
while (fgets(line, sizeof(line), stream)) {
// Just stream, not *stream
count++;
}
return count;
}
Function call:
int noOfLines = SCAN(stream);
// Just stream, not &stream.

How to read each individual lines of a text file into their own individual variables

Hi guys I am in the second weekend of trying to find the solution to this problem. I am new at c programming and I have been trying to read each individual line of a text file and pass each of them to their own variable, where I will be able to manipulate them(such as compare them, do calculations etc).
I have a code to read each individual lines but I am unsure how to pass each line to a variable, here is the code:
#include <stdlib.h>
#include <stdio.h>
struct line_reader {
FILE *f;
char *buf;
size_t siz;
};
void
lr_init(struct line_reader *lr, FILE *f)
{
lr->f = f;
lr->buf = NULL;
lr->siz = 0;
}
char *
next_line(struct line_reader *lr, size_t *len)
{
size_t newsiz;
int c;
char *newbuf;
*len = 0;
for (;;) {
c = fgetc(lr->f);
if (ferror(lr->f))
return NULL;
if (c == EOF) {
if (*len == 0)
return NULL;
else
return lr->buf;
} else {
if (*len == lr->siz) {
newsiz = lr->siz + 4096;
newbuf = realloc(lr->buf, newsiz);
if (newbuf == NULL)
return NULL;
lr->buf = newbuf;
lr->siz = newsiz;
}
lr->buf[(*len)++] = c;
if (c == '\n')
return lr->buf;
}
}
}
void
lr_free(struct line_reader *lr)
{
free(lr->buf);
lr->buf = NULL;
lr->siz = 0;
}
int
main()
{
struct line_reader lr;
FILE *f;
size_t len;
char *line;
f = fopen("file.txt", "r");
if (f == NULL) {
perror("foobar.txt");
exit(1);
}
lr_init(&lr, f);
while (line = next_line(&lr, &len)) {
fputs("1: ", stdout);
fwrite(line, len, 1, stdout);
}
if (!feof(f)) {
perror("next_line");
exit(1);
}
lr_free(&lr);
return 0;
}
Any help would be appreciated.
What about using an array simply as a suggestion
e.g.)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char** readFile(const char *filename, size_t *lineCount){
FILE *fp;
char buff[4096];
size_t lines = 0, capacity=1024;
char **line;
if(NULL==(fp=fopen(filename, "r"))){
perror("file can't open.");
return NULL;
}
if(NULL==(line=(char**)malloc(sizeof(char*)*capacity))){
perror("can't memory allocate.");
fclose(fp);
return NULL;
}
while(NULL!=fgets(buff, sizeof(buff), fp)){
line[lines++] = strdup(buff);
if(lines == capacity){
capacity += 32;
if(NULL==(line=(char**)realloc(line, sizeof(char*)*capacity))){
perror("can't memory allocate.");
fclose(fp);
return NULL;
}
}
}
*lineCount = lines;
fclose(fp);
return (char**)realloc(line, sizeof(char*)*lines);
}
void freeMem(char** p, size_t size){
size_t i;
if(p==NULL) return;
for(i=0;i<size;++i)
free(p[i]);
free(p);
}
int main(){
size_t lines;
char **line;
if(NULL!=(line=readFile("file.txt", &lines))){//lines: set line count of file
printf("%s", line[25]);// 26th line of file, zero origin
}
freeMem(line, lines);
return 0;
}
On any POSIX-compliant system just use the m scan modifier:
for ( char *line, nl; scanf("%m[^\n]%c",&line,&nl) != EOF ; free(line) ) {
if ( !line )
strcpy(line=malloc(1),""), getchar();
// ...
}
m has been in the standard for five years now.

Resources