Reading different datatype from .txt file - c

I want to read data from a text file and store the data.
I can not all the data using getc() as it will take all the data at once, and I do not know how to distribute that for my use.
Data is in form of:
John
Sebastian
1
2 //Number of notes(So, when I read this value and run a loop to collect all
notes)
12 //note 1
21 //note 2
#include <stdio.h>
struct StudentDetails
{
char firstName[100], secondName[100];
int notes[100][30], id;
struct StudentDetails *next;
};
int main()
{
FILE *input;
input = fopen("input.txt", "r");
if (!input)
{
while (input != EOF)
{
//what to do to store in different variable rather in one.
}
}
else
{
printf("File not found");
}
}

Please try fread() function for reading a record from a file and fwrite(), it's used to write a record to the file.
eg: fwrite(&sd,sizeof(sd),1,input);
for student record no need of struct StudentDetails *next; (we are not doing anything like linked list, we just write different student record in a file. So you just define structure variable as StudentDetails SD in main that is more than enough each iteration of loop you can write one student record to file.)
for reading you can use
while(fread(&sd,sizeof(sd),1,input) > 0 )
{
printf("Name:%s",sd.name);//this you can do ...
}
I hope it will help you :)

Related

Display record function to display Non-empty records not displaying records

Setting up a database which takes the input from a user(First name, last name, ID number , etc..) and inputs the information into a binary file, to update information , delete records, and update any information provided. All other functions seem to be functioning properly(Dont mind the bad code, im fairly new to programming) besides the function to display the non empty records. the information seems to be getting saved into the files because the other functions have access to it(all the same file pointer). I've checked to see if the file was being overwritten by the initialization of the empty file and that hasn't been the case to my understanding.
I've checked to see if the file was being overwritten by the initialization of the empty file and that hasn't been the case to my understanding. I've also tried updating the the if statement in the DisplayRecord function so that it would read all files and display only the ones that have an established ID number but it still shows null when the function is ran.
// fopen opens the file; exits if file cannot be opened
if ((cPtr = fopen("patient.dat", "rb")) == NULL) {
puts("File could not be opened.");
}//end If
else {
printf( "Patient ID\t Last Name\t first name\t DOB \tGender\t Doctor ID\t
Doctor last name\t Room Number\n" );
struct PatientData {
unsigned int Pat_ID; //ID number
char F_Name[25];//first name
char L_Name[25]; //last name
char Phone_num[20] ; //Phone number
char gender[2];
unsigned int doctor_ID;
char doc_LN[25];
unsigned int room_num;
char DoB[10];
};
//read all records until eof
while(!feof(cPtr)){
//create blank set to compare to data on file
struct PatientData Patient= { 0, "","","","",0,"", 0,"" };
int result=fread(&Patient,sizeof(struct PatientData), 1 , cPtr);
if(result!=0 && Patient.Pat_ID!=0){
printf("%-d%-15s%-15s%-10s%-12s%-15d%-15s%-10d\n",
Patient.Pat_ID,
Patient.L_Name,Patient.F_Name,Patient.DoB,Patient.gender,
Patient.doctor_ID, Patient.doc_LN,Patient.room_num);
}
fclose(cPtr); // fclose closes the file
Its suppose to display all records that have information in it. but the actual output is not showing any records.

Creating a file with the name of a structure i just read from another file

I am trying to read a structure from the file f and i need some arrays of that structure ( "nume" and "firma.nrang") to be written into another file with the name of "localitate" which is also an array of the structure i am reading.
If two structures from f have the same "localitate" array, then their "nume" and "firma.nrang" fields need to be written in the same file called "localitate". I hope i explained well enough. However, i dont know why i cannot open the files i am creating, which i specifically wanted to be text and not binary. What is the problem?
This is my code which doesnt work properly:
typedef struct
{
char localitate[10];
int nrang;
} FIRMA;
typedef struct
{
char nume[20];
int varsta;
FIRMA firma;
} ANG;
ANG x;
FILE *p;
for (i=0; i<m+n; i++)
{
fread(&x,sizeof(x),1,f);
p=fopen(x.firma.localitate,"a");
if (p==NULL)
{
printf("eroare");
exit (1);
}
fwrite(&x.nume,sizeof(x.nume),1,p);
fwrite(&x.firma.nrang,sizeof(x.firma.nrang),1,p);
fclose(p);
}

Loading from file to linked list

I am trying to load an unknown amount of data from a file in to a linked list
Load Function
void load(FILE *file, Node **head) // while feof somewhere
{
char tempArtist[30]={'\0'}, tempAlbum[30]={'\0'}, tempTitle[30]={'\0'}, tempGenre[30]={'\0'},tempSpace='\0';
char tempPlay[100]={'\0'}, tempRating[6]={'\0'}, tempMins[8]={'\0'}, tempSecs[8]={'\0'};
Data *temp;
temp=(Data*)malloc(sizeof(Data));
while(!feof(file))
{
fscanf(file,"%s",tempArtist);
fscanf(file,"%s",tempAlbum);
fscanf(file,"%s",tempTitle);
fscanf(file,"%s",tempGenre);
fscanf(file,"%s",tempMins);
fscanf(file,"%s",tempSecs);
fscanf(file,"%s",tempPlay);
fscanf(file,"%s",tempRating);
temp->mins=strdup(tempMins);
temp->secs=strdup(tempSecs);
temp->album=strdup(tempAlbum);
temp->artist=strdup(tempArtist);
temp->genre=strdup(tempGenre);
temp->song=strdup(tempTitle);
temp->played=strdup(tempPlay);
temp->rating=strdup(tempRating);
insertFront(head,temp);
}
}
The problem I am having is that when I go to print out the list all the entries are the same as the last one read from the file. This is something to do with the strdup() but I can't get it to copy to the data type without getting access violations.
What is another method(proper method) that I could use to copy the strings read from the file and pass them to the insert?
InsertFront
void insertFront(Node **head, Data *data)
{
Node *temp=makeNode(data);
if ((*head) == NULL)
{
*head=temp;
}
else
{
temp->pNext=*head;
*head=temp;
}
}
Data struct
typedef struct data
{
char *artist;
char *album;
char *song;
char *genre;
char *played;
char *rating;
char *mins;
char *secs;
}Data;
testing file
snoop
heartbeat
swiggity
rap
03
10
25
4
hoodie
cakeboy
birthday
hiphop
02
53
12
5
You use the same instance of temp for all your lines. The allocation should go inside the loop, ideally after you have established that the whole entry was read in successfully.
By the way, feof is not a good way to control input loops. You should check the return value of fscanf instead.
while (1) {
if (fscanf(file,"%s",tempAlbum) < 1 ) break;
if (fscanf(file,"%s",tempArtist) < 1) break;
// ...
temp = (Data *) malloc(sizeof(Data));
temp->album=strdup(tempAlbum);
temp->artist=strdup(tempArtist);
// ...
insertFront(head, temp);
}
Note how the allocation of a new node happens only after a whole record was read.
There are other ways to improve the code. For example you have very short buffers for the strings that contain numerical data. What if there is a line slip-up and you read a longer line into into such a short buffer? Also, your input seems to be line-wise, so it might be good to use fgets instead of fscan(f, "%s"), which will only read "words" and will have problems with lines that have spaces.
while(!eof) is wrong. You can do like.
for (;;) {
ret = fscanf()
if(ret == EOF) break;
}

Updating and deleting contents of a file

I have a file named as Empdata.txt having fields as "(%s)id,(%s)name,(%d)salary". Firstly, i am inserting some values to it. Now i want to update record having the same id as given by the user. I am using this code:
struct employee
{
char id[100];
char name[100];
int sal;
};
int main()
{
FILE *ptr;
struct employee e;
ptr=fopen("Empdata.txt","w+");
printf("Enter Employee id");
scanf("%s",id);
while(!feof(ptr))
{
fread(&e,sizeof(e),1,ptr);
if(strcmp(id,e.id)==0)
{
printf("Enter name");
scanf("%s",e.name);
printf("Enter basic salary");
scanf("%d",&e.sal);
fwrite(&e,sizeof(e),1,ptr);
}
};
fclose(ptr);
}
But it is not matching the ids. So it is not updating even. Further i have to perform delete operation also. I am not getting how to delete record having a particular id.
Please assume all variables are initialized properly.
If you plan to update a record, you will have to both read, and write records. Hence the "w" file mode is insufficient (ie:fopen("Empdata.txt","w");). Perhaps the "r+" mode would be more appropriate?
First thing in your while() loop, you need to read a record from your file.
At the bottom of the loop, you need to note your file position (ie:ftell()), so that if the next record is a match, you will know where to fseek() back to in order to write the updated record back to the file.
long position=0;
...
while(!feof(ptr))
{
fread(&e,sizeof(e),1,ptr);
if(strcmp(id,e.id)==0)
{
...
}
position=ftell(ptr);
};
If you find a matching record (ie:if(strcmp(id,e.id)==0)), the very last thing you should do is re-position to the beginning of the matching record (ie:fseek()) and then write the updated record. And since you have accomplished your task, you should break out of the while loop and return.
{
...
fseek(ptr, position, SEEK_SET);
fwrite(&e,sizeof(e),1,ptr);
}

C File Handling / Structure Problem

How does one read in a txt file containing names and marks of students and inputting them
into an array of structures.
maximum allowable records are 7:
e.g. James 45
Mary 70
Rob 100
First, define the structure. The structure describes what a record is; what data it contains. Here you have a student's name and his or her mark.
Second you need to prepare the array to write the objects of the structure into. You already know from the problem description that no more than 7 students are allowed, so you can define the length of the array to that number.
Next, open the text file.
Lastly write a loop that takes as input from the file a string for the student's name and an integer (or a floating-point point number if you so choose) for their mark. In the loop create a structure for each record and insert the structure into the array.
And of course, don't forget to close the file when you're done.
That's all there is to it. If you have any syntax or logic questions then ask in the comments, and we'll gladly help.
Read the man page for fopen: http://linux.die.net/man/3/fopen
This should give you somewhere to start.
Also, the man page for fread and fgets could be helpful. There are many ways to read from a file and the path you choose will depend on numerous things, such as the structure of the file and the amount of security you want in your application.
found this code that is similar enough that should be able to help you get done what you need.
#include <stdio.h>
#include <string.h>
/* Sample data lines
5 0 Wednesday Sunny
6 2 Thursday Wet
*/
int main() {
/* Define a daydata structure */
typedef struct {
int n_adults; int n_kids;
char day[10]; char weather[10];
} daydata ;
daydata record[30];
FILE * filehandle;
char lyne[121];
char *item;
int reccount = 0;
int k;
/* Here comes the actions! */
/* open file */
filehandle = fopen("newstuff.txt","r");
/* Read file line by line */
while (fgets(lyne,120,filehandle)) {
printf("%s",lyne);
item = strtok(lyne," ");
record[reccount].n_adults = atoi(item);
item = strtok(NULL," ");
record[reccount].n_kids = atoi(item);
item = strtok(NULL," ");
strcpy(record[reccount].day,item);
item = strtok(NULL,"\n");
strcpy(record[reccount].weather,item);
printf("%s\n",record[reccount].day);
reccount++;
}
/* Close file */
fclose(filehandle);
/* Loop through and report on data */
printf("Weather Record\n");
for (k=0; k<reccount; k++) {
printf("It is %s\n",record[k].weather);
}
}
http://www.wellho.net/resources/ex.php4?item=c209/lunches.c
Give a holler with code you tried if you have problems changing it to fit your needs.

Resources