我的C程序有问题。我想从文件中删除选中的行。 处理两个文件,删除工作正常,但删除程序后不会更改文件名,也不会删除" old"文件。
文件结构
"new","new","new","1001"
"asd","as","das","asd"
"sdasda","asasd","dsaa","sdsda"
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define DB "db.txt"
int main()
{
FILE *f1;
FILE *f2;
char ch;
int linia, tmp = 1;
f1 = fopen(DB, "r");
printf(" \n Enter line number:");
scanf("%d", &linia);
f2 = fopen("kopia.txt", "a+");
ch = getc(f1);
while (ch != EOF)
{
ch = getc(f1);
if (ch == '\n')
{ tmp++; }
if (tmp != linia)
{putc(ch, f2);}
}
fclose(f1);
fclose(f2);
remove(DB); //not working
rename("kopia.txt",DB); //not working
printf("\n Done:\n");
return 0;
}
答案 0 :(得分:1)
DB应该是字符串类型的宏,但我在代码中看到的是db.txt wihout“,只需将其替换为”db.txt“并尝试..
由于此错误,不应编译此代码,是吗?
另外,重命名(“kopia.txt”,DB)确保从IDE外部运行此应用程序时,文件kopia.txt存在于exe文件附近。
答案 1 :(得分:1)
...
int ch;
while (1)
{
ch = getc(f1);
if (ch == EOF) break;
if (ch == '\n') tmp++;
if (tmp != linia) putc(ch, f2);
}
...