簡體   English   中英

一旦讀取文本文件,是否可以從文本文件中刪除第一個字符?

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

閱讀后,是否可以刪除文本文件中的第一個字符? 我希望程序從文本文件中讀取字符,並且一旦使用它就應該刪除從文本文件中讀取的當前字符。

您不能在文件的開頭插入,在開頭刪除,在中間插入,在文件中間刪除而不重寫。 最后可以附加。 有時可以在最后刪除(取決於平台)。

根據您的需求和系統,您可能對管道感興趣。 至少他們能夠勝任您想要他們做的事情。 盡管管道用於進程間通信。

對於Linux,請看這里

對於Windows,請點擊此處

您不能從文件中刪除字符,可以對其進行修改,並在邏輯上說數據已刪除。

我們無法刪除文件內容。 您可以在要刪除文件中char的位置添加*(或文件中不存在的任何內容)來代替刪除。

在多次刪除后,文件中有很多*。 只需將文件中除*之外的整個文件復制到新文件

刪除舊文件,將新文件重命名為舊文件

要么

您只需在要刪除的部分之后復制數據即可。

參見以下代碼:

#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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM