In: Computer Science
I got a problem in C struct. I made a aa.txt file and read data by struct. I am learning how to pass variable and value between function by pointers.
The first line in txt (integer 5) means I need to read the next five lines data to struct
aa.txt
5
111
222
333
444
555
*********************************************************************
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int i,totalRow;
char inBuf[20];
char str[20];
void readData();
void sum() ;
typedef struct demo{
int num;
}demo1;
int main()
{
struct demo demo1;
struct demo *sptr;
sptr= &demo1;
sum(sptr);
return 0;
}
void readData(struct demo *ptr)
{
int i,j;
FILE *fin = NULL;
fin = fopen("aa.txt", "r");
if (fin == NULL)
{
printf("Could not open the file.\n");
}
fgets(str, sizeof(str), fin);
sscanf(str,"%d ",&totalRow);
printf("%d\n",totalRow);
for(i = 0; i {
fgets(str,sizeof(str),fin);
sscanf(str,"%d ", &ptr->num);
printf("%d\n", ptr->num);
}
fclose(fin);
return;
}
//find the sum
void sum(struct demo *ptr)
{
int result;
readData(ptr);
printf("the sum is %d\n", ptr->num);
return;
}
*******************************************************************************
My code of sum function is wrong, I have no idea how to pass the data to sum function from readData function.
readData function can read the data from the file, it works.
Maybe the problem is still in the readData function, because I guess I did not store the data to memory(I am not sure)
Thanks
Below is the working code , leave comments in case of any doubt :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int i,totalRow;
char inBuf[20];
char str[20];
void readData();
void sum() ;
typedef struct demo{
int num;
}demo1;
int main()
{
struct demo demo1;
struct demo *sptr;
sptr= &demo1;
sum(sptr);
return 0;
}
void readData(struct demo *ptr)
{
int i,j, temp = 0;
FILE *fin = NULL;
fin = fopen("aa.txt", "r");
if (fin == NULL)
{
printf("Could not open the file.\n");
}
fgets(str, sizeof(str), fin);
sscanf(str,"%d ",&totalRow);
printf("%d\n",totalRow);
for(i = 0; i < totalRow ; ++i ){
fgets(str,sizeof(str),fin);
sscanf(str,"%d ", &ptr->num);
temp += ptr->num; //Adding each value of file
printf("%d\n", ptr->num);
}
fclose(fin);
ptr->num = temp;
return;
}
//find the sum
void sum(struct demo *ptr)
{
int result;
readData(ptr);
printf("the sum is %d\n", ptr->num);
return;
}
Output screentshot:
