Is there a way to delete the first character from a text file once it is read?

房东的猫 提交于 2019-12-11 06:36:27

问题


Is there any way to delete the first character in a text file once you read it? I want the program to read the character in from the text file and once it is used it should delete that current character that was read from the text file.


回答1:


you can't delete characters from file,you can modify them and logically says that data was deleted.

we can't remove file content. instead of deleting you can add * (or any thing that is not there in your file) at the position where you want to delete char in file.

after many more deletions there are lot * 's in your file. just copy your entire file except *'s in your file to new file

remove old file rename new file to old file

or

you just copy the data after the part you delete over the part you want deleted..

See this code:

#include <stdio.h>
#include <stdlib.h>

int main(){

FILE *fp = fopen("file.txt","r+"); /* Open for reading  and writing */
FILE *fp1=fopen("new.txt","a+");
FILE *fp2=fopen("new2.txt","a+");

char ch;
int i=0,n;

printf("Enter how many characters do you want to delete from file\n ");
scanf("%d",&n);
while(((ch = fgetc(fp)) != EOF )&&( i<n))
{
fseek(fp,-1,SEEK_CUR);
fputc('*',fp);
i++;
}

printf("file after delete\n");
rewind(fp);
while((ch = fgetc(fp)) != EOF )
{
if(ch!='*')
printf("%c",ch);
}

printf("copy to another file after delete\n");
rewind(fp);
while((ch = fgetc(fp)) != EOF )
{
if(ch!='*')
fputc(ch,fp1);
}


printf("file after delete\n");
rewind(fp);
while((ch = fgetc(fp)) != EOF )
{
if(ch!='*')
printf("%c",ch);
}


printf("delete first n characters from new.txt delete\n");

printf("Enter how many characters do you want to delete from file\n ");
scanf("%d",&n);
i=0;
rewind(fp1);
while((ch = fgetc(fp1)) != EOF )
{
if(i>n)
fputc("%c",ch);
i++;
}



printf("\n\n");
fclose(fp);
fclose(fp1);
fclose(fp2);
//use rename() and remove() functions to delete old file and then rename new file as old one.
return 0;
}



回答2:


You cannot insert at the beginning, remove at the beginning, insert in the middle, remove in the middle of a file without rewriting it. Appending at the end is possible. Sometimes it's possible to delete at the end (depending on the platform).




回答3:


Depending on your needs and system, you might be interested in pipes. At least they are capable of what you want them to do. Though pipes are meant for interprocess communication.

For Linux look here.

For Windows look here.



来源:https://stackoverflow.com/questions/18801884/is-there-a-way-to-delete-the-first-character-from-a-text-file-once-it-is-read

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!