Author Topic: deleting stored records on txt files  (Read 3151 times)

dreamcuts

  • Guest
deleting stored records on txt files
« on: April 14, 2019, 06:10:17 am »
so i am currently playing around with some coding as shown below, but for some reason when i try to delete a stored book in the original txt file. for some  reason it just doesn't delete.
could it be related to it not being able to find the right line where the books for say are being stored on the txt file?
i have attached a screenshot of the prompt aswhile, and i am wanting for when someone choice like number 1 for instant that it would remove the first book in the screenshots case "help help 123"

//DELETE RECORD
int deletedata(struct Book*h)
{
    FILE*fptr;
    FILE*fptrnew;
    char bookdel;
    int delete_line, temp=1, ret;
    fptr=fopen("books.txt", "r");
    bookdel = getc(fptr);
    while (bookdel != EOF)
    {
        printf("%c", bookdel);
        bookdel = getc(fptr);
    }
    rewind(fptr);
    printf(" \nEnter line number of the line to be deleted:");
    scanf("%d", &delete_line);
    fptrnew=fopen("[censored].txt", "w"); //open new file in write mode
    bookdel=getc(fptr);
    while (bookdel != EOF)
    {
        bookdel=getc(fptr);
        if (bookdel != '\n')
        {
            temp++;
        }
        if (temp != delete_line) //except the line to be deleted
        {
            putc(bookdel, fptrnew); //copy all lines in file [censored].txt
        }
    }
    fclose(fptr);
    fclose(fptrnew);
    remove("books.txt");
    rename("[censored].txt", "books.txt"); //rename the file [censored].txt to books.txt
    /*
    ret=rename("[censored].txt", "books.txt");
    if(ret == 0)
    {
        printf("\nFile renamed successfully");
    }
    else
    {
        printf("\nError: unable to rename the file\n");
    }
    */
    fptr=fopen("books.txt", "r");
    bookdel=getc(fptr);
    printf("\nThe new book list is as follows:\n");
    while (bookdel != EOF)
    {
        printf("%c", bookdel);
        bookdel = getc(fptr);
    }
    fclose(fptr);
    printf("\nPress any key to continue.\n");
    getch();
}

Online stahta01

  • Lives here!
  • ****
  • Posts: 7582
    • My Best Post
Re: deleting stored records on txt files
« Reply #1 on: April 14, 2019, 06:58:21 am »
Is reading the rules a foreign idea before posting on a website!

 http://forums.codeblocks.org/index.php/topic,9996.0.html
C Programmer working to learn more about C++ and Git.
On Windows 7 64 bit and Windows 10 64 bit.
--
When in doubt, read the CB WiKi FAQ. http://wiki.codeblocks.org