bachra04
asked on
erase contents of file
Hi experts,
I need to know how to erase the contents of a file in c and then write new information.
(see attached code )
Thanks.
I need to know how to erase the contents of a file in c and then write new information.
(see attached code )
Thanks.
I don't see attached code, but
#include <stdio.h>
FILE *F=fopen("file","w");
fputs("new information",F);
fclose(F);
will erase the contents of a file in c and then write new information
ASKER
if ((fp = fdopen(pfd, "r+")) == NULL) {err(EXIT_FAILURE, "fdopen");
}
pollv[0].fd = pfd;
pollv[0].events = POLLIN;
pollv[0].revents = 0;
while(1) {
rc = poll(pollv, 1, 15000);
if (rc > 0 && pollv[0].revents)
{
if ((rc = read(pfd, result, sizeof(result))) == -1) {
printf(" INE 98 error read");
}
if (strcmp(res, "val1"))
{
// here is my problem I want to erase the contents of the file
// then write the following
fprintf(fp,
"xx::%s\n"
"id::%d\n"
"ee::%d\n",
"mama", "232", 22);
fflush(fp);
}
}
}
ASKER
That was my attached code the difficulty I had is that I cannot close and open the file at the same time.
Before the fprintf
rewind (fp);
rewind (fp);
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
First I open the file to read from it
then based on the data I got I will erase the data
and then I need to write new data to it.
what you are suggesting is that I need to close the file
then open it in write Mode then put my data ?
then based on the data I got I will erase the data
and then I need to write new data to it.
what you are suggesting is that I need to close the file
then open it in write Mode then put my data ?
> what you are suggesting is that I need to close the file then open it in write Mode then put my data ?
If you open the file with "r+" you can both read and write to the file.
As @cup said, after you read the data from the file, rewind it to the beginning and then write your new data. When you close the file, it will be truncated to the correct size.
If you open the file with "r+" you can both read and write to the file.
As @cup said, after you read the data from the file, rewind it to the beginning and then write your new data. When you close the file, it will be truncated to the correct size.
Using StreamWriter would create a new file and if the file already exists, The content of the file will be erased. You can also use StreamWriter to append text to a file but you want to remove the content. The following code is used in the C# Programming Language
First, We need to define our object.
Open in new window
Then, We should close the StreamWriter in order to access this file by another process or application
Open in new window
Thank you, I hope this helps :)