I want to write and read a Student struct to/from a file. The program works weird . Sometimes reads 52 elements, sometimes 1 element. I couuld not see what the problem is. Help please.

int main()
{
	FILE *deneme = openBinaryFile("C:\\text\\text.txt");
	Student me = {"Mert","Akcakaya",200611004, 0};
	Student you = {"Default", "Default", 111111111, 0};
	insertRecord(deneme, me);
	readRecord(deneme,&you,1);
	printf("%d %d %s %s", you.deleted, you.studentID, you.name, you.surname);
	deleteRecord(deneme,1);
	printf("isDeleted = %d", isRecordDeleted(deneme,1));
	return 0;
}
int insertRecord(FILE *file, const Student student)
{
	unsigned long int studentID[1];
	int deleted[1];
	int check = 0;

	fseek(file,0,SEEK_END);
	studentID[0] = student.studentID;
	deleted[0] = student.deleted;

	check += fwrite(deleted, sizeof(int), 1, file);
	check += fwrite(studentID, sizeof(unsigned long int), 1, file);
 	check += fwrite(student.name, sizeof(char), 30, file);
	check += fwrite(student.surname, sizeof(char), 50, file);
	fflush(file);
	return (check == 82);
}

int isRecordDeleted(FILE *file, int position)
{
	int deleted[1];
	fseek(file, totalStudentSize * (position-1), SEEK_SET );
	fread(deleted, sizeof(int), 1, file);
	if(deleted[0] == 1)
	{
		printf("File was deleted");
		return 1;
	}
	else 
		return 0;
}

int readRecord(FILE *file, Student* student, int position)
{
	int check = 0;
	unsigned long int studentID[1];
	int deleted[1];
	fseek(file, totalStudentSize * (position-1), SEEK_SET);
	if( !feof(file) )//Should skip the statement when the position is bigger then the biggest position in the file, but does not...
	{
		check += fread(deleted, sizeof(int), 1, file);
		check += fread(studentID, sizeof(unsigned long int), 1, file);
		check += fread(student->name, sizeof(char), 30,  file);
		check += fread(student->surname,  sizeof(char), 50, file);
		student->deleted = deleted[0];
		student->studentID = studentID[0];
	}
	else
		printf("Not accurate position for reading!", stderr);
	
	return ( check == 82 );
}

int deleteRecord(FILE *file, int position)
{
	int deleted[1] = {1};
	fseek(file, totalStudentSize * (position-1), SEEK_SET);
	return fwrite(deleted, sizeof(int), 1, file) == 1;
}

So this 'Student struct' what is it?

You should use struct for ID && names . And you can raad from struct and write to text file also you can read from file to struct.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.