read data from file into array of structures - c

Hi I'm trying to read data from file into array of structures I tried to use fgets but got the error saying that RECORD type cannot be convert to char* this is what i have so far
#include <stdio.h>
#include <stdlib.h>
#define MAX_NAME 20
#define FILE_NAME 50
#define LIST_SIZE 50
//void getData(RECORD name[], RECORD score)
typedef struct RECORD
{
char *name;
float score;
}RECORD;
int main (void)
{
// Declarations
FILE *fp;
char fileName[FILE_NAME];
RECORD list[LIST_SIZE];
int count = 0;
// Statements
printf("Enter the file name: ");
gets(fileName);
fp = fopen(fileName, "r");
if(fp == NULL)
printf("Error cannot open the file!\n");
while (fgets(list[count], LIST_SIZE, fp) != NULL)
{
count++;
}
return 0;
}
the error occurs in the fgets statement inside while loop, how can i fix this and read data into array of structures?
thank in advance

fgets is used to input a string from a text file one line as a unit.
e.g.)
char input_line_buff[128];
fgets(input_line_buff, 128, fp);
read-in
input_line_buff:(contents eg) "name 66.6\n"
you do split , memory alloc and copy, and convert .
e.g.)
list[count].name = strdup("name");
list[count].score= atof("66.6");
count++;

Try this,
while(fgets((char *)list[count], SIZE/* data size to be read */, fp) != NULL)
{...}

Related

Am I using typedef structures and arrays correctly to read my file? It is not opening

I'm a beginner in data structures with C, I have taken C programming but I've only touched a little bit on structures in the course and I have not kept up with it.
Anyways, I'm trying to make a program that will read data into an array of structures from a file and print out the contents of the array you have populated. I need help figuring this out.. I'm honestly not too sure if I'm doing this correctly either... :/
Any help is greatly appreciated, and thank you in advance! :)
This is what I tried so far
Here's my code:
FYI - The file I'm trying to open is DataFile.txt
#include<stdio.h>
#include <stdlib.h>
#define SIZE 10
#define ARRAY_SIZE 30
//Struct contains 3 fields, name, age, salary
typedef struct
{
char name[SIZE];
int age;
int salary;
} data;
data a[ARRAY_SIZE];
FILE * fp = fopen("DataFile.txt", "r");
if (fp == NULL)
{
printf("Error %s.\n", strerror(errno));
exit(1);
}
int GetData()
{
int i = 0;
fscanf(fp, "%s", a[i].name);
while(fp && i<ARRAY_SIZE)
{
fscanf(fp, "%d", &a[i].age);
fscanf(fp, "%d", &a[i].salary);
i++;
}
return i;
}
void ShowData( int records_read)
{
//Print text file data on screen
for(int i=0;i<records_read;i++)
{
printf("%s %d %d\n", a[i].name, a[i].age, a[i].salary);
}
}
int main()
{
char name[256];
int i = 0;
int records_read;
//Call the method, getData
i = GetData();
//Prompt and read input from the user
printf("Pick a number from 1 to 10:");
scanf("%d", &records_read);
//Call the method, showData
ShowData(records_read);
fclose(fp);
return 0;
}
The program works if I don't put this part of the code in:
FILE * fp = fopen("DataFile.txt", "r");
if (fp == NULL)
{
printf("Error %s.\n", strerror(errno));
exit(1);
}
BUT the output is just a list of zeros..
A quick answer: At first, try to split FILE * fp = fopen("DataFile.txt", "r"); into two parts as one is the variable declaration FILE * fp = NULL; and the other one is the assignment expression fp = fopen("DataFile.txt", "r");. And then keeps the part of the variable declaration out of all the functions, while moves both the part of the assignment and the if-statement if (fp == NULL){...} into function GetData(). The code might work in this case.

File is getting created but data is not pushed into the file

I have written this C program, where it takes system calls as input like ps -f or ls /tmp, etc and output from the system call is pushed to a file and then from the file it reads and displays the output.
Here output file is getting created /tmp/j but there is no data present inside it. Can some one please help me with this issue and Thanks in advance.
My program.
#include<stdio.h>
#include<sys/syscall.h>
#include <stdlib.h>
main()
{
enum msgtype {PROCESS_LIST_REQUEST=1, PROCESS_LIST_RESPONSE, DIRECTORY_LIST_REQUEST, DIRECTORY_LIST_RESPONSE, ERROR_REQUEST};
struct head{
int version;
int msg_length;
int header_length;
enum msgtype msg_type;
char data;
char *reqtype;
};
struct head *buf;
char buff[10];
buf = malloc((sizeof(struct head)));
buf->reqtype=malloc(40);
char req[10];
printf("type ps -f on the console \n");
fgets(req, sizeof(req),stdin);
buf->reqtype = req;
printf("%s" , buf->reqtype);
snprintf(buff, sizeof(buff), "%s>/tmp/j", buf->reqtype);
printf("%s \n",buff);
system(buff);
{
FILE *fp;
char c;
fp = fopen("/tmp/j", "r");
if (fp == NULL)
printf("File doesn't exist\n");
else
{
do {
c = getc(fp); /* get one character from the file*/
putchar(c); /* display it on the monitor*/
} while (c != EOF); /* repeat until EOF (end of file) */
}
fclose(fp);
}
}
There are a couple of errors in your code.
1) Allocate some memory greater than 10 for your buff. 10 is not enough. Your string is exceeding the size of 10. I made it 20 in my machine and checked.
2) fgets(req, sizeof(req),stdin); is reading a \n at the end of the string. Delete the last character. req[strlen(req) - 1] = '\0';
See this for man page of fgets

How to read in txt file in CSV format and save into array in C

I am new to C and I need to read in a .txt file where there are 3 fields in each line separated by a comma, and I need to save it into an array. I am wondering how to do this?
Here is an example file:
0, "test", 100
1, "hi", 2
2, "goodbye", 0
So I am wondering how to read the file line by line and to store each element into an array. I have started by defining a struct:
typedef struct data {
int col1;
char *col2;
int col3;
} data_t;
Could anyone help me out to get started with the file opening?
The SQLite shell has an .import command that reads CSV. It is worthy of study. You can find it here; search for CSVReader to see how it's coded.
For file opening there is a standard library (include stdio.h) function named fopen. It has the following declaration:
FILE *fopen(const char *filename, const char *mode);
As you can see it expects you to provide a pointer to const char for both filename and mode (read/write/read+write). It will return a pointer to a FILE so inside the function where you intend to work with it you'd have to declare one like this:
FILE *my_file;
It's also a good idea to initialize it to NULL so that you can check for errors when using fopen.
In your main function (purely for reading):
FILE *my_file = NULL;
my_file = fopen("filename.txt", "r");
And check for the returned pointer:
if (my_file == NULL)
//error message etc.
simply sample(check omit)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUMOFDATA 10
typedef struct data {
int col1;
char *col2;
int col3;
} data_t;
int main(){
data_t data_array[NUMOFDATA];
int data_count = 0;
char line[128];
FILE *fp;
fp=fopen("data.txt", "r");
while(fgets(line, sizeof(line), fp)){
int col1, col3;
char col2[64];
if(sscanf(line, "%d, %63[^,], %d", &col1, col2, &col3)==3){
char *cl2p = col2;
data_array[data_count].col1 = col1;
data_array[data_count].col3 = col3;
if(col2[0] == '"'){
char *p = strchr(&col2[1], '"');
if(p)
*p = '\0';
cl2p = &col2[1];
}
data_array[data_count].col2 = strdup(cl2p);
//printf("%d, \"%s\", %d\n",data_array[data_count].col1,data_array[data_count].col2,data_array[data_count].col3);
if(++data_count == NUMOFDATA)break;
}
}
fclose(fp);
return 0;
}

allocate memory and read input from file to arrays of structures

I have question about reading data from file to structures
when I tried to run this code i get unhandled exception Access violation reading location 0xcccccce0, The error occur inside the getData function, Why am I getting this error, how Should I fix the code ?
this is my input file
4
A,10
B,12
C,60
D,120
tutorY
my intention in the getData function was to first read the first line to get then number 4, then use that number to allocate for student structure and then read the next four lines of the file in to student structure fields and then read the last line into tutorname feild in the TUTOR structure.
thank in advance
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "queue.h"
#include "stack.h"
#define RECORDS_SIZE 100
#define NAME_SIZE 20
typedef struct Student
{
char nameStudent[NAME_SIZE];
int TimeIn;
int TimeUpdate;
}STUDENT;
typedef struct TUTOR
{
char nameTutor[NAME_SIZE];
int TutorTIme;
STUDENT *ptr;
}TUTOR;
QUEUE *queue1;
STACK *stack1;
void getData(STUDENT *studentArr[RECORDS_SIZE], TUTOR tutorArr[1]);
int main (void)
{
STUDENT *studentArr[RECORDS_SIZE];
TUTOR tutorArr[1];
FILE *fp = NULL;
getData(studentArr, tutorArr);
return 0;
}
void getData(STUDENT *studentArr[RECORDS_SIZE], TUTOR tutorArr[1])
{
FILE *fp;
char fileName[NAME_SIZE];
char buffer[RECORDS_SIZE];
int first = 0;
int count = 1;
printf("Enter file name: ");
gets(fileName);
fp = fopen(fileName, "r");
if (fp == NULL)
{
printf("Error! The file does not exist!\n");
}
fscanf(fp,"%d",&first);
*studentArr = (STUDENT*) malloc(first*sizeof(STUDENT));
while( fgets(buffer, first +1, fp) != NULL)
{
if (count <= first)
{
sscanf(buffer, "%[,]%d", studentArr[count]->nameStudent, studentArr[count]->TimeIn);
printf("%s,%d", studentArr[count]->nameStudent, studentArr[count]->TimeIn);
}
else
sscanf(buffer, "%s", tutorArr[count].nameTutor);
count++;
}
return;
}
There's a couple of problems I have spotted.
The first fscanf reading first will read the first number then leave the rest of the line ("\n") to be picked up by the first call to fgets
More importantly, studentArr is an array of pointers, presumably one element for each student, but the malloc allocates only the first pointer in sudentArr, all the others contain garbage, which is causing the access violation.
fix like this
void getData(STUDENT **studentArr, TUTOR tutorArr[1]);//change
int main (void)
{
STUDENT *studentArr;//change
TUTOR tutorArr[1];
FILE *fp = NULL;//not use
getData(&studentArr, tutorArr);//change
return 0;
}
void getData(STUDENT **studentArr, TUTOR tutorArr[1])
{
FILE *fp;
char fileName[NAME_SIZE];
char buffer[RECORDS_SIZE];
int first = 0;
int count = 1;
printf("Enter file name: ");
gets(fileName);//has risk
fp = fopen(fileName, "r");
if (fp == NULL)
{
printf("Error! The file does not exist!\n");
return;//add, can't continue
}
fscanf(fp,"%d\n",&first);//add, consumption '\n'
*studentArr = (STUDENT*) malloc(first*sizeof(STUDENT));
while( fgets(buffer, RECORDS_SIZE, fp) != NULL)//change buffer size
{
if (count <=first)//
{
sscanf(buffer, "%[^,],%d", (*studentArr)[count-1].nameStudent, &(*studentArr)[count-1].TimeIn);//add, `,` and -1 to count is 1 origin, `&` need for "%d"
printf("%s,%d\n", (*studentArr)[count-1].nameStudent, (*studentArr)[count-1].TimeIn);
++count;//need count up
}
else
sscanf(buffer, "%s", tutorArr[0].nameTutor);
}
return;//need allocate record size return to main
}
Some more problems:
count should be initialised to 0 not 1 because your array is zero-indexed.
You're not incrementing count in your loop
Allocate memory for each student inside the loop with studentArr[count] = new Student();
Prefer strtok to sscanf` to split the buffer into fields. Much easier to deal with the comma following the string.

reading first line of a file in c

I am very new to C and I am having trouble with the most fundamental ideas in C. We are starting structures and basically the assignment we are working on is to read a delimited file and save the contents into a structure. The first line of the file has the number of entries and alls that I am trying to do at the moment is get the program to read and save that number and print it out. Please do not assume I know anything about C I really am very new to this.
This code is giving me a segmentation fault
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct info{
char name[100];
char number[12];
char address[100];
char city[20];
char state[2];
int zip;
};
int strucCount;
char fileText[1];
int main(char *file)
{
FILE *fileStream = fopen(file, "r");
fgets(fileText, 1, fileStream);
printf("\n%s\n",fileText);
fclose(fileStream);
}
Here is the sample file
4
mike|203-376-5555|7 Melba Ave|Milford|CT|06461
jake|203-555-5555|8 Melba Ave|Hartford|CT|65484
snake|203-555-5555|9 Melba Ave|Stamford|CT|06465
liquid|203-777-5555|2 Melba Ave|Barftown|CT|32154
Thanks for everyones comments, they helped a lot, sorry to Jim. I am working on very little sleep and didn't mean to offend anyone, I am sure we have all been there haha.
SUGGESTION:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXLINE 80
#define MAXRECORDS 10
struct info{
char name[100];
char number[12];
char address[100];
char city[20];
char state[2];
int zip;
};
int
main(int argc, char *argv[])
{
FILE *fp = NULL;
int nrecs = 0;
char line[MAXLINE];
struct info input_records[MAXRECORDS];
/* Check for cmd arguments */
if (argc != 2) {
printf ("ERROR: you must specify file name!\n");
return 1;
/* Open file */
fp = fopen(argv[1], "r");
if (!fp) {
perror ("File open error!\n");
return 1;
}
/* Read file and parse text into your data records */
while (!feof (fp)) {
if (fgets(line, sizeof (line), fp) {
printf("next line= %s\n", line);
parse(line, input_records[nrecs]);
nrecs++;
}
}
/* Done */
fclose (fp);
return 0;
}
fclose(fileStream);
}
Key points:
Note use of "argc/argv[]" to read input filename from command line
line, nrecs, etc are all local variables (not globals)
Check for error conditions like "filename not given" or "unable to open file"
Read your data in a loop, until end of input file
Parse the data you've read from the text file into an array of binary records (TBD)

Resources