我使用以下代码从我的基本C程序填充一个短词典:
void main () {
FILE *fp;
fp = fopen("c:\\CTEMP\\Dictionary2.txt", "w+");
fprintf(fp, Word to Dictionary");
但是,我还希望删除某些我不想再写在字典中的单词。我做了一些研究,我知道
"您无法从文件中删除内容,并将剩余内容向下移动。您只能追加,截断或覆盖。
您最好的选择是将文件读入内存,在内存中处理,然后将其写回磁盘"
如何在没有“我想删除”字样的情况下创建新文件?
由于
答案 0 :(得分:4)
如果您需要做的操作要复杂得多,那么您可以直接将其读入内存"使用mmap(),但这是一种更高级的技术;你需要将文件视为没有零终止符的字节数组,并且有很多方法可以搞砸了。
答案 1 :(得分:0)
我使用了以下代码:
printf("Enter file name: ");
scanf("%s", filename);
//open file in read mode
fileptr1 = fopen("c:\\CTEMP\\Dictionary.txt", "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 = getc(fileptr1);
while (ch != EOF)
{
ch = getc(fileptr1);
if (ch == '\n')
{
temp++;
}
//except the line to be deleted
if (temp != delete_line)
{
//copy all lines in file replica.c
putc(ch, fileptr2);
}
}
fclose(fileptr1);
fclose(fileptr2);
remove("c:\\CTEMP\\Dictionary.txt");
//rename the file replica.c to original name
rename("replica.c", "c:\\CTEMP\\Dictionary.txt");
printf("\n The contents of file after being modified are as follows:\n");
fileptr1 = fopen("c:\\CTEMP\\Dictionary.txt", "r");
ch = getc(fileptr1);
while (ch != EOF)
{
printf("%c", ch);
ch = getc(fileptr1);
}
fclose(fileptr1);
scanf_s("%d");
return 0;
}