How can I write int value Binary and txt file in C? - c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
struct student
{
int stuNum;
int point;
};
int newStudent(FILE* dataf, FILE* indexf);
int main(void)
{
FILE* datafile;
FILE* indexfile;
indexfile = fopen("indexDosyasi.txt", "a+");
datafile = fopen("veriDosyasi.bin", "wb+");
newStudent(datafile, indexfile);
fclose(datafile);
fclose(indexfile);
return 0;
}
int newStudent(FILE* dataf, FILE* indexf)
{
indexf = fopen("indexfile.txt", "a+"); // txt file
dataf = fopen("datafile.bin", "wb"); // binary file
if (dataf == NULL)
{
printf("error");
return -1;
}
struct student* last = (struct student*)malloc(sizeof(struct student));
printf("number of student \n");
scanf("%d", last->stuNum);
fprintf(indexf, "%d\t", last->stuNum);
fwrite(last, sizeof(struct student), 1, dataf);
// fwrite(&last->stuNum,sizeof(struct student),1,dataf);
return 0;
}
Hi , i am trying student add system with c , my datafile have to be binary file and my indexfile have to be txt file , stuNum and point have to be int value but i cant add stunum and point into datafile and indexfile , i dont understand how can i add ? i read a lot answer about this question but i didnt find answer i want .When i run this code and enter the student number is 875,it says 66955608268424 in the indexfile(txt) and it says �*~ in the datafile(binary).i cant understand where is mistake?
Can you help me?

Try this way:
int newStudent(...)
{
write(fileName, "what you want to write", strlen("what you want to write"))
}
And if it doesn't works, try to tranform your int to a character string. I thing it is the itoa() or atoi() function.

Related

How to read a file with mixture of data in C?

I am trying to read a file that is like
91242 FirstName1_LastName1 3.02
I try to use fscanf to read the file and I am confused how to read the second element that with a mixture of character and int. I'm just using one statement to read for test only. I will modify it to a while loop to read the whole text file.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include "linked_list.h"
int main() {
node *list_head = NULL;
FILE *file;
file = fopen("student.txt", "r");
if (file == NULL) {
printf("Can not find the file.\n");
}
else {
printf("File students.txt opened successfully.\n");
printf("Linked list built from file students.txt successfully\n");
}
student s;
fscanf(file,"%d%s%lf", &s.id,s.name,&s.gpa);
insert_last(&list_head, s);
print_list(list_head);
}
Here is what i got when I print it out.
91242 FirstName1_LastName1)\�#�4� 3.02
Here is my student.c document
#include "student.h"
void print_student(student student_record){
printf("%d\t%s\t%.2f\n", student_record.id, student_record.name,
student_record.gpa);
}
And here is the definition of student.
 typedef struct{ int id; char name[20]; double gpa; } student;

Segmentation Fault when writing to a file in C

Whenever I attempt to write to a file, I am getting a segmentation fault. I don't have any access to software that can tell me where it's coming from since I'm at school. If anyone could help me out that would be great.
//OLMHash.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "OLMHash.h"
int main()
{
createAccount();
return 0;
}
struct account createAccount()
{
struct account *newAccount;
newAccount = (struct account *)malloc(sizeof(struct account));
printf("Enter userid: ");
scanf("%s", newAccount->userid);
printf("\nEnter password: ");
scanf("%s", newAccount->password);
char *output = malloc(sizeof(char) * 255);
strcpy(output, newAccount->userid);
strcat(output, "\t");
strcat(output, newAccount->password);
FILE* fp;
fp = fopen("accountslist.txt", "r");
fputs(newAccount->userid, fp);
free(output);
}
-
//OLMHash.h
struct account
{
char userid[32];
char password[12];
};
struct account createAccount();
You opened the file for reading instead of writing, and you did not check the action succeeded. Try
fp = fopen("accountslist.txt", "w");
if(fp == NULL) {
// get out code
exit(1);
}
When calling fopen, I was opening it for reading rather than writing. I physically created the file that way I can leave it as "reading"

Reading random struct array element from binary file

I have an very big array (100k) in which elements are randomly placed with array index as primary key. I am trying to figure out a way to access array elements with fseek using index key as offset. For some reason no matter what offset i give, I get null back. Following is the simple representation of the problem.
Help appreciated. Sorry if this is a repost. I could not find similar question asked anywhere.
#include <stdlib.h>
#include <stdio.h>
typedef struct student
{
char *name;
int marks;
}student;
student class[] = {
[5]{"Jack",34},
[12]{"Jane",56},
[53]{"Joe",72}
};
main()
{
FILE *f, *f1;
student rec;
f = fopen("student.data", "wb");
fwrite(class, sizeof(student), sizeof(class), f);
fclose(f);
if((f1 = fopen("student.data","rb"))==NULL)
{
printf("\nError in Opening File\n");
exit(0);
}
/* I want to seek to 12th element in the array and print 'Jane' */
fseek(f1, sizeof(student) * 12, SEEK_SET);
fread(&rec, sizeof(student), 1, f1);
printf("Name:%s\n", rec.name);
fclose(f1);
}
Your example works for me. The only thing I had to change was to use double quotes instead of single quotes for the class array initialization:
cat student.c; gcc student.c; ./a.out
gives the following output:
#include <stdlib.h>
#include <stdio.h>
typedef struct student
{
char *name;
int marks;
}student;
student class[] = {
[5]{"Jack",34},
[12]{"Jane",56},
[53]{"Joe",72}
};
main()
{
FILE *f, *f1;
student rec;
f = fopen("student.data", "wb");
fwrite(class, sizeof(student), sizeof(class), f);
fclose(f);
if((f1 = fopen("student.data","rb"))==NULL)
{
printf("\nError in Opening File\n");
exit(0);
}
/* I want to seek to 12th element in the array and print 'Jane' */
fseek(f1, sizeof(student) * 12, SEEK_SET);
fread(&rec, sizeof(student), 1, f1);
printf("Name:%s\n", rec.name);
fclose(f1);
}
Name:Jane

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.

Resources