Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delete a specific line from text file in C?

Tags:

c

Example:

George 50 40
Lime 30 20
Karen 10 60

do {
    printf("\nInput player name:[1..10] ");
    fgets(name,10,stdin);
}

Input name: Lime

Then the text file will be:

George 50 40
Karen 10 60

like image 447
Hansen Derrick Avatar asked Dec 21 '13 07:12

Hansen Derrick


People also ask

What is remove () function in C?

C library function - remove() The C library function int remove(const char *filename) deletes the given filename so that it is no longer accessible.

How do I delete a specific line?

Delete lines or connectorsClick the line, connector, or shape that you want to delete, and then press Delete. Tip: If you want to delete multiple lines or connectors, select the first line, press and hold Ctrl while you select the other lines, and then press Delete.

How do you go to a specific line in a file in C?

If you know the length of each line, you can use fseek to skip to the line you want. Otherwise, you need to go through all lines. Show activity on this post. buffer =(char*)malloc(sizeof(char) * strlen(line));

How to remove a specific line from a text file?

Read the line number from the user, and delete the specific line from the existing file. Then print the modified content file. The source code to remove a specific line from the text file is given below.

How to remove a specific line from text file using GCC?

Read the line number from the user, and delete the specific line from the existing file. Then print the modified content file. The source code to remove a specific line from the text file is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

How do I remove an item from a text file?

To remove an item from a text file, first move all the text to a list and remove whichever item you want. Then write the text stored in the list into a text file:

How do I skip a line in a file in Python?

You can open the original file with r+ and store its contents into an array (following these steps ). Then you can use a for loop to scan the array for the line you want to skip, and delete that line.


2 Answers

Consider a file like an array. If we want to delete an element at index i of an array, we shift all elements from i+1 one step towards left and then logically reduce the size of array.

I am applying same princliple on files. In the end ftruncate() is used to reduce the size of file and hence removing the end parts of the file.This code works fine for large files too, as at any time only one byte is being stored in memory.

#include<errno.h>
#include<unistd.h>
#include<stdio.h>
/*
 * Description: fdelete() deletes 'bytes' bytes of data from the stream pointed to by fp. 
 *              bytes will be deleted from the CURRENT FILE POSITION.
 *              File must be opened in read + write mode while passing file pointer 
 *              to this function.
 *              File position before calling the function and after the 
 *              function returns will be the same.
 * Return Values: returns 0 on success and errno on failure. Kindly use perror("") 
 *                to print error if non-0 return value returned.
 */
int fdelete(FILE* fp, int bytes) {
    
    // to store each byte/char from file
    char byte;
    long readPos = ftell(fp) + bytes, writePos = ftell(fp), startingPos = writePos;
    // start reading from the position which comes after the bytes to be deleted
    fseek(fp, readPos, SEEK_SET);
    while (fread(&byte, sizeof(byte), 1, fp)) {
        // modify readPos as we have read right now
        readPos = ftell(fp);
        // set file position to writePos as we are going to write now
        fseek(fp, writePos, SEEK_SET);
        
        // if file doesn't have write permission
        if (fwrite(&byte, sizeof(byte), 1, fp) == 0) 
            return errno;
        // modify writePos as we have written right now
        writePos = ftell(fp);
        // set file position for reading
        fseek(fp, readPos, SEEK_SET);
    }

    // truncate file size to remove the unnecessary ending bytes
    ftruncate(fileno(fp), writePos);
    // reset file position to the same position that we got when function was called.
    fseek(fp, startingPos, SEEK_SET); 
    return 0;
}
like image 112
Vishwesh Pujari Avatar answered Sep 27 '22 22:09

Vishwesh Pujari


Try this:

 /* C Program Delete a specific Line from a Text File
 */
#include <stdio.h>

int main()
{
    FILE *fileptr1, *fileptr2;
    char filename[40];
    char ch;
    int delete_line, temp = 1;

    printf("Enter file name: ");
    scanf("%s", filename);
    //open file in read mode
    fileptr1 = fopen(filename, "r");
    ch = getc(fileptr1);
   while (ch != EOF)
    {
        printf("%c", ch);
        ch = getc(fileptr1);
    }
    //rewind
    rewind(fileptr1);
    printf(" \n Enter line number of the line to be deleted:");
    scanf("%d", &delete_line);
    //open new file in write mode
    fileptr2 = fopen("replica.c", "w");
    ch = 'A';
    while (ch != EOF)
    {
        ch = getc(fileptr1);
        //except the line to be deleted
        if (temp != delete_line)
        {
            //copy all lines in file replica.c
            putc(ch, fileptr2);
        }
        if (ch == '\n')
        {
            temp++;
        }
    }
    fclose(fileptr1);
    fclose(fileptr2);
    remove(filename);
    //rename the file replica.c to original name
    rename("replica.c", filename);
    printf("\n The contents of file after being modified are as follows:\n");
    fileptr1 = fopen(filename, "r");
    ch = getc(fileptr1);
    while (ch != EOF)
    {
        printf("%c", ch);
        ch = getc(fileptr1);
    }
    fclose(fileptr1);
    return 0;
}

Reference - http://www.sanfoundry.com/c-program-delete-line-text-file/

like image 30
user3115056 Avatar answered Sep 27 '22 20:09

user3115056