Why this program?
This simple c example is answer to below questions.
How can i delete some specific line from .txt file?
Is there a way of deleting the whole line using c program?
How to delete a line in a file C Programming?
Here are simple steps to do;
1) Open a temp file for writing.
2) Open the xyz.txt file for reading. ie source file.
3) copy from source file to temp file using gets().
4) compare the char or string to be deleted is there from gets, if it is there dont copy that line to temp file, else copy.
5) Close both files
6) Delete the xyz.txt file
7) Rename the temp file, to xyz.txt.
And here is C program that would delete the first or last line from a file.
#include
#define CORN_CONF_FILE "/var/spool/cron/crontabs/root"
#define CORN_CONF_TMP_FILE "/var/spool/cron/crontabs/tmp"
int del_cron_conf_line();
int main()
{
int ret;
ret = del_cron_conf_line();
printf("ret=%d",ret);
return 0;
}
int del_cron_conf_line()
{
int ret=-1,j=0;
char tmp_str[50];
FILE *fp,*temp;
fp = fopen(CORN_CONF_FILE, "r");
temp = fopen(CORN_CONF_TMP_FILE,"wb");
if((fp != NULL) && (temp != NULL))
{
while(fgets(tmp_str,50,fp) != NULL)
{
printf("%s \n",tmp_str);
if(strstr(tmp_str,"halt"))
{
j=ftell(fp);
}
else
fputs(tmp_str,temp);
}
printf("fptr j=%d",j);
fclose(fp);
fclose(temp);
system("rm /var/spool/cron/crontabs/root");
system("cp /var/spool/cron/crontabs/tmp /var/spool/cron/crontabs/root");
ret = 0;
}
else
{
ret = -1;
printf("fopen err %s\n",temp);
fclose(temp);
}
return ret;
}
enjoy.
This simple c example is answer to below questions.
How can i delete some specific line from .txt file?
Is there a way of deleting the whole line using c program?
How to delete a line in a file C Programming?
Here are simple steps to do;
1) Open a temp file for writing.
2) Open the xyz.txt file for reading. ie source file.
3) copy from source file to temp file using gets().
4) compare the char or string to be deleted is there from gets, if it is there dont copy that line to temp file, else copy.
5) Close both files
6) Delete the xyz.txt file
7) Rename the temp file, to xyz.txt.
And here is C program that would delete the first or last line from a file.
#include
#define CORN_CONF_FILE "/var/spool/cron/crontabs/root"
#define CORN_CONF_TMP_FILE "/var/spool/cron/crontabs/tmp"
int del_cron_conf_line();
int main()
{
int ret;
ret = del_cron_conf_line();
printf("ret=%d",ret);
return 0;
}
int del_cron_conf_line()
{
int ret=-1,j=0;
char tmp_str[50];
FILE *fp,*temp;
fp = fopen(CORN_CONF_FILE, "r");
temp = fopen(CORN_CONF_TMP_FILE,"wb");
if((fp != NULL) && (temp != NULL))
{
while(fgets(tmp_str,50,fp) != NULL)
{
printf("%s \n",tmp_str);
if(strstr(tmp_str,"halt"))
{
j=ftell(fp);
}
else
fputs(tmp_str,temp);
}
printf("fptr j=%d",j);
fclose(fp);
fclose(temp);
system("rm /var/spool/cron/crontabs/root");
system("cp /var/spool/cron/crontabs/tmp /var/spool/cron/crontabs/root");
ret = 0;
}
else
{
ret = -1;
printf("fopen err %s\n",temp);
fclose(temp);
}
return ret;
}
enjoy.
Comments