Thread: Deleting a line from a file

  1. #1

    Deleting a line from a file

    I have a program that is supposed to delete records from a file, I tried opening the file to read and write and using fgets to input each line. I'd then sscanf the input to a string and test to see if one of the items in the line is the record. If it is then I use continue to skip it and if it isn't then I fputs the line back into the file.

    Supposedly this should leave the file as it was except without the one line I wanted to delete, but it's not working at all. Here's the code
    int delete_rec()
    	unsigned long number;
    	char buffer[500],
    	struct cust TEMP;
    	printf("\nDELETE RECORD");
    		printf("Error opening cust.dat for delete");
    		return (1);
    	printf("\nCustomer Number:");
    	scanf("%d", &number);
    	while(fgets(buffer, sizeof(buffer), fpt) != NULL){
    		sscanf(pInput, "%d%*c%49[^;]%*c%49[^;]%*[^OoSs]%c", &,, 
    			TEMP.add, &TEMP.status);
    		if( == number)
    		fputs(buffer, fpt);
    	if(fclose(fpt) == EOF){
    		printf("Error closing file\a\n");
    		return 1;
    	printf("\n\nDeleted. Press ENTER to continue.\n");
    	return 0;

  2. #2
    I found a problem with the loop, but it still doesn't work, here's the change.
    	while(fgets(buffer, sizeof(buffer), fpt) != NULL){
    		strncpy(pInput, buffer, 500);
    		sscanf(pInput, "%d%*c%49[^;]%*c%49[^;]%*[^OoSs]%c", &,, 
    			TEMP.add, &TEMP.status);
    		if( == number){
    			fputs(buffer, fpt);

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    It's very hard to modify a text file like this, because line lengths can change.

    It's much simpler to simply create another file with all the changes, then do a delete/rename when you're done.

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. File transfer- the file sometimes not full transferred
    By shu_fei86 in forum C# Programming
    Replies: 13
    Last Post: 03-13-2009, 12:44 PM
  3. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  4. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM