Delete A Specific Line From A File | C Programming Example

preview_player
Показать описание
Рекомендации по теме
Комментарии
Автор

I am a beginner in C, I try to watch some videos on how can I read a specific line but I cannot find a single video about it, But with your video I gain some an idea on how can I achieve it. thanks!

fraios
Автор

I'm new to C, but this method sounds like its pretty heavy, workload wise.

Is there not a more efficient way to delete a particular line? You mentioned something about it in the beginning of your video.

I know you can move to a specific location in the file and overwrite that particular spot, but that only changes the values in question, not free space. Is there a way to go about it or do I have to get all the data out of the file no matter what?

Kyriakos
Автор

I'm so confused, the only way I can get this code to not also delete the last line is if I rewrite the do while loop like this:

do
{
// Scan line
fgets(buffer, MAX_LINE, file);

if (feof(file)) {
keep_reading = false;
}
else if (current_line == delete_line) {
current_line++;
continue;
}

fputs(buffer, tmp);
current_line++;
} while(keep_reading);


I don't understand why the above would work any differently than the way you wrote it.

bsykesbeats
Автор

Thanks you very much. It is really working

nathanaelkamkamdem
Автор

Hello. I tried your code but there is a problem. When ı try to delete a line for the first time, it deletes the last line also. After doing this procces 1 time, second time do not delete the new file's last line. What could be wrong ?

FILE *fp, *fpp;

char file_name[SIZE];
char temp_file_name[SIZE];
char buffer[SIZE];
int delete_line=0;

printf("WHAT IS THE NAME OF YOUR FILE : ");
scanf("%s", file_name);
strcpy(temp_file_name, "temp____");
strcat(temp_file_name, file_name);
printf("WHICH LINE YOU WANT TO DELETE : ");
scanf("%d", &delete_line);

fp = fopen(file_name, "r");
fpp = fopen(temp_file_name, "w");
if(fp=='\n' || fpp=='\n'){
printf("ERROR OPENING FILES \n");
return 1;
}

bool keep_reading=true;
int current_line=1;
do{
fgets(buffer, SIZE, fp);

if(feof(fp))
keep_reading=false;

else if(current_line!=delete_line)
fputs(buffer, fpp);

current_line++;

}
while(keep_reading);
fclose(fp);
fclose(fpp);
int a = remove(file_name);
if(a==0)
{
printf("COPY PROGRES IS COMPLETED !");
}

emirhandemir
Автор

source code works like a charm, but I have a problem.
temporary file not being renamed. I have made your code into a function and set filename into an argument. filename when called, filename was correct. opened. and read.

Randomname
Автор

What environment are you using right now?

myonlylovejesus
Автор

I need code without using temporary file broo but its helpful

prabhuteja