Thread: Update Record & Delete Record in File.

  1. #1
    Registered User
    Join Date
    May 2008
    Posts
    8

    Update Record & Delete Record in File.

    Hello Guyz,

    Code:
    struct student
    {
    	char name[20];
    	char semCode[10];
    	int enrollNo;
    	int assignSub;
    	int marks;
    	int attendence;
    };
    I have this structure. everything is working fine except i am having problems as to how should i remove the record of a particular student or Update.

    addStudentRecord is working fine.
    updateStudentRecord is under construction.
    deleteStudentRecord is under construction.

    Code:
    struct student var;
    FILE *ptr;
    
    void refresh()
    {
    	fclose(ptr);
    	ptr = fopen("c:\\file.txt","a+");
    }
    void addStudentRecord()
    {
    	fflush(stdin);
    	printf("Enter name:\n");
    	gets(var.name);
    
    	fflush(stdin);
    	printf("Enter Semester Code:\n");
    	gets(var.semCode);
    
    	fflush(stdin);
    	printf("Enter Enrollment Number:\n");
    	scanf("%d",&var.enrollNo);
    	
    	var.assignSub=0;
    	var.marks=-1;
    
    	fwrite(&var,sizeof(struct student),1,ptr);
    
    	printf("Data Entered Successfully\n");
    	printf("Press any key..");
    	refresh();
    	getch();
    }
    void updateStudentRecord()
    {
    	int enrollNo;
    	int counter=0;
    	int records = getNoOfRecords();
    
    	fflush(stdin);
    	printf("Enter Enrollment Number:\n");
    	scanf("%d",&enrollNo);
    
    	while(counter!=records)
    	{
    		fread(&var,sizeof(struct student),1,ptr);
    		if(var.enrollNo==enrollNo)
    		{
    			
    		}
    		counter++;
    	}
    }
    void deleteStudentRecord()
    {
    	int enrollNo;
    	int counter=0;
    	int records = getNoOfRecords();
    
    	fflush(stdin);
    	printf("Enter Enrollment Number:\n");
    	scanf("%d",&enrollNo);
    
    	while(counter!=records)
    	{
    		fread(&var,sizeof(struct student),1,ptr);
    		if(var.enrollNo==enrollNo)
    		{
    			var.name[0]='\0';
    			var.semCode[0]='\0';
    			var.enrollNo=-1;
    			var.assignSub=0;
    			var.marks=-1;
    		}
    		counter++;
    	}
    	fwrite(&var,sizeof(struct student),1,ptr);
    	refresh();
    }

  2. #2
    Registered User
    Join Date
    Apr 2008
    Posts
    396
    how should i remove the record of a particular student or Update.
    To update a record, you can simply fseek() to point back at the record beginning in the file and then proceed as when you write data. To remove, this is a bit less easy, you could for instance swap the current record and the very last one in the file and truncate the file (to pop the last record). The 'truncation' part is system-dependent (this problem was discussed in another thread, try to find it). Or you can rewrite the entire file too, which is not that bad (depending on your program performance constraints).

  3. #3
    Registered User
    Join Date
    May 2008
    Posts
    8
    The old fashion way.

    I am actually quite puzzled that wherever i have looked at i mean in books and searched the net all over. Everyone keep suggesting me the same idea. create another file copy all the the data except the one you want to delete then delete the file and rename the new one to old one.

    theres got to be way to actually delete some real time data in a file !!

    I will wait for an answer !

  4. #4
    Registered User
    Join Date
    Apr 2008
    Posts
    396
    The truncation method doesn't suit you? because it looks like you didn't read that part of the reply.

    EDIT: if there's no solution to easily erase random bytes in a file is that for most filesystems, the actual data is divided in blocks and dispatched on the disk, deleting data would imply to reorganize all those blocks, which is an operation very specific to the filesystem and to the operating system, as far as I know there's no mean to achieve that. But you can rewrite yourself your data and then truncate the file, this is much more acceptable (for the FS it only implies to deallocate the last blocks).
    Last edited by root4; 05-17-2008 at 06:30 PM.

  5. #5
    Registered User
    Join Date
    May 2008
    Posts
    8
    I have done it the old fashion way...

    But my rename and remove functions are not working in deleteStudentRecord

    Code:
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    #include<io.h>
    #include<fcntl.h>
    
    struct student
    {
    	char name[20];
    	char semCode[10];
    	int enrollNo;
    	int assignSub;
    	int marks;
    	int attendence;
    };
    struct student var;
    FILE *ptr;
    
    void refresh()
    {
    	fclose(ptr);
    	ptr = fopen("c:\\file.txt","a+");
    }
    void addStudentRecord()
    {
    	refresh();
    	fflush(stdin);
    	printf("Enter name:\n");
    	gets(var.name);
    
    	fflush(stdin);
    	printf("Enter Semester Code:\n");
    	gets(var.semCode);
    
    	fflush(stdin);
    	printf("Enter Enrollment Number:\n");
    	scanf("%d",&var.enrollNo);
    	
    	var.assignSub=0;
    	var.marks=-1;
    
    	fwrite(&var,sizeof(struct student),1,ptr);
    
    	printf("Data Entered Successfully\n");
    	printf("Press any key..");
    	refresh();
    	getch();
    }
    void updateStudentRecord()
    {
    	int enrollNo;
    	int counter=0;
    	int records = getNoOfRecords();
    
    	refresh();
    	fflush(stdin);
    	printf("Enter Enrollment Number:\n");
    	scanf("%d",&enrollNo);
    
    	while(counter!=records)
    	{
    		fread(&var,sizeof(struct student),1,ptr);
    		if(var.enrollNo==enrollNo)
    		{
    			
    		}
    		counter++;
    	}
    }
    void deleteStudentRecord()
    {
    	int enrollNo;
    	int counter=0;
    	
    
    	FILE *ptr2 = fopen("c:\\file2.txt","a");
    
    	int records = getNoOfRecords();
    
    	refresh();
    	fflush(stdin);
    	printf("Enter Enrollment Number:\n");
    	scanf("%d",&enrollNo);
    
    	while(counter!=records)
    	{
    		fread(&var,sizeof(struct student),1,ptr);
    		if(var.enrollNo==enrollNo)
    		{
    
    		}
    		else
    		{
    			fwrite(&var,sizeof(struct student),1,ptr2);
    		}
    		counter++;
    	}
    	fcloseall();
    	remove("c:\\file.txt");
    	rename("c:\\file2.txt","c:\\file.txt");
    	printf("Press any key..");
    	getch();
    }
    
    void markAttendence()
    {
    
    }
    void enterMarks()
    {
    
    }
    int fileSize()
    {
    	int length;
    	int des;
    
    	des = open("c:\\file.txt",O_RDONLY,0);
    	length = lseek(des, 0, SEEK_END);
    
    	return length;
    }
    int getNoOfRecords()
    {
    	return (fileSize()/(sizeof(struct student)));
    }
    void print()
    {
    	system("cls");
    	printf("Name:");
    	puts(var.name);
    	printf("\n");
    
    	printf("Semester Code:");
    	puts(var.semCode);
    	printf("\n");
    
    	printf("Enrollment Number:");
    	printf("%d",var.enrollNo);
    	printf("\n\n");
    
    	printf("Assignment Submitted:");
    	if(var.assignSub==0)
    	{
    		printf("Not Entered!\n\n");
    	}
    	else if(var.assignSub==1)
    	{
    		printf("Not Submitted!\n\n");
    	}
    	else if(var.assignSub==2)
    	{
    		printf("Submitted!\n\n");
    	}
    
    	printf("Marks:");
    	if(var.marks==-1)
    	{
    		printf("Not Entered!\n\n");
    	}
    	else
    	{
    		printf("%d",var.marks);
    		printf("\n\n");
    	}
    	printf("Press any key...\n");
    	getch();	
    }
    void searchByName()
    {
    
    	char name[20];
    	int counter=0;
    	int records = getNoOfRecords();
    
    	refresh();
    	fflush(stdin);
    	printf("Enter Name:\n");
    	gets(name);
    
    	while(counter!=records)
    	{
    		fread(&var,sizeof(struct student),1,ptr);
    		if(!(strcmp(name,var.name)))
    		{
    			print();
    		}
    		counter++;
    	}	
    }
    void searchBySemesterCode()
    {
    	char semCode[10];
    	int counter=0;
    	int records = getNoOfRecords();
    
    	refresh();
    	fflush(stdin);
    	printf("Enter Semester Code:\n");
    	gets(semCode);
    
    	while(counter!=records)
    	{
    		fread(&var,sizeof(struct student),1,ptr);
    		if(!(strcmp(semCode,var.semCode)))
    		{
    			print();
    		}
    		counter++;
    	}
    }
    void searchByEnrollmentNumber()
    {
    	int enrollNo;
    	int counter=0;
    	int records = getNoOfRecords();
    
    	refresh();
    	fflush(stdin);
    	printf("Enter Enrollment Number:\n");
    	scanf("%d",&enrollNo);
    
    	while(counter!=records)
    	{
    		fread(&var,sizeof(struct student),1,ptr);
    		if(var.enrollNo==enrollNo)
    		{
    			print();
    		}
    		counter++;
    	}
    }
    void search()
    {
    	int a=0;
    
    	while(a!=4)
    	{
    		system("cls");
    		printf("1.Search by Name:\n");
    		printf("2.Search by Semester Code:\n");
    		printf("3.Search by Enrollment Number:\n");
    		printf("4.Exit\n");
    		printf("Enter:");
    		
    		fflush(stdin);
    		scanf("%d",&a);
    
    		switch(a)
    		{
    			case 1:
    				searchByName();
    				break;
    			case 2:
    				searchBySemesterCode();
    				break;
    
    			case 3:
    				searchByEnrollmentNumber();
    				break;
    
    			case 4:
    				return;
    				break;
    
    			default:
    				printf("Invalid Option!!\n");
    				break;
    		}
    	}
    }
    
    void main()
    {
    	int a=0;
    
    	ptr = fopen("c:\\file.txt","a+");
    
    	while(a!=7)
    	{
    		system("cls");
    		printf("Select an Option:\n");
    		printf("1.Add Student Record\n");
    		printf("2.Update Student Record\n");
    		printf("3.Delete Student Record\n");
    		printf("4.Mark Attendence\n");
    		printf("5.Enter Marks\n");
    		printf("6.Search\n");
    		printf("7.Exit\n");
    		printf("Enter:");
    		
    		scanf("%d",&a);
    
    		switch(a)
    		{
    			case 1:
    				addStudentRecord();
    				break;
    			
    			case 2:
    				updateStudentRecord();
    				break;
    
    			case 3:
    				deleteStudentRecord();
    				break;
    
    			case 4:
    				markAttendence();
    				break;
    
    			case 5:
    				enterMarks();
    				break;
    
    			case 6:
    				search();
    				break;
    
    			case 7:
    				exit(0);
    				break;
    
    			default:
    				printf("Invalid Option\n");
    				break;
    		}
    	}
    }

  6. #6
    Registered User
    Join Date
    Apr 2008
    Posts
    396
    But my rename and remove functions are not working in deleteStudentRecord
    Code:
    	remove("c:\\file.txt");
    	rename("c:\\file2.txt","c:\\file.txt");
    Here's a good advice: always check the return status of the functions you call. Every standard function proposes a mean to tell whether it has succeeded or failed and often you can get a detailed explanation (cf errno, strerror(),...). You cannot simply call all those functions and assume everything will be allright everytime, besides you should apply the same rule to your functions.

    So check the status of the functions that fail and you'll get your answer.

  7. #7
    Registered User
    Join Date
    May 2008
    Posts
    8
    both return -1

  8. #8
    Registered User
    Join Date
    Apr 2008
    Posts
    396
    both return -1
    then call strerror(errno);* to get the explanation or output the value of errno and check its meaning in your documentation.

    *requires to include additional files: errno.h, string.h

    EDIT: As additional information here's the general behavior of standard functions:
    RETURN VALUE
    On success, zero is returned. On error, -1 is
    returned, and errno is set appropriately.

  9. #9
    Registered User
    Join Date
    May 2008
    Posts
    8
    it says permission denied when i call the remove method !!

  10. #10
    Registered User
    Join Date
    May 2008
    Posts
    8
    Can anyone run my program on their pc and check why is it giving permission denied error!! I have written this code in vc++ 6.0;

  11. #11
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by unsafe_pilot1 View Post
    The old fashion way.

    I am actually quite puzzled that wherever i have looked at i mean in books and searched the net all over. Everyone keep suggesting me the same idea. create another file copy all the the data except the one you want to delete then delete the file and rename the new one to old one.

    theres got to be way to actually delete some real time data in a file !!

    I will wait for an answer !
    The answer is <drum roll please>:

    You don't actually delete a record, when you delete a record! You have a field in the record that you mark, telling your database that this record is current, or that the record is not current, and it can be over-written with a new record.

    When the database records become too "fragmented", (too many old records, no longer a part of the current database), then the entire database may be "compacted". Finally, old records are overwritten by active records, and thus finally, deleted.

    It's a clever trick.

  12. #12
    Registered User
    Join Date
    May 2008
    Posts
    8
    yes i know... deleting the data so that it creates fragments and then using a tool to defragment the data. Well i am not writing a commercial program i just want to remove and rename the file. Looks like the handle is not released by the fcloseall() method or the file is still in use when its being removed can you check it ?

    I don't program in c that much...i code in java.

  13. #13
    Registered User
    Join Date
    Apr 2008
    Posts
    396
    yes i know... deleting the data so that it creates fragments and then using a tool to defragment the data.
    You don't have to go that far, but nevermind.

    Looks like the handle is not released by the fcloseall() method or the file is still in use when its being removed can you check it ?
    Even if someone tries it and find out that it works, would it solve your problem? You should try to find why it doesn't work in your case. Try to isolate the relevant part of you code and build the smallest code that reproduce the error, then you will be able to understand and fix it.
    You should also try to review your whole code, the refresh() function is useless, don't use fflush(stdin) (cf FAQ) and at last notice that for fcloseall(): "the standard streams (stdin, stdout and stderr) are also closed.". and be sure to check the status of every I/O call you use.

  14. #14
    Registered User
    Join Date
    May 2008
    Posts
    8
    well it worked and everytime it so happens that a stupid mistake was overlooked.

    Thanks root4 for your quick response. I learned couple of new things from you.

    Mistake was:

    Code:
    int fileSize()
    {
    	int length;
    	int des;
    
    	des = open("c:\\file.txt",O_RDONLY,0);
    	length = lseek(des, 0, SEEK_END);
    
    	close(des);//FORGOT TO CLOSE THE FILE !!
    
    	return length;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A development process
    By Noir in forum C Programming
    Replies: 37
    Last Post: 07-10-2011, 10:39 PM
  2. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM
  3. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  5. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM