How can I clear the contents of a file - c

I would like to know how the contents of a file can be cleared in C. I know it can be done using truncate, but I can't find any source clearly describing how.

The other answers explain how to use truncate correctly... but if you found yourself on a non-POSIX system that doesn't have unistd.h, then the easiest thing to do is just open the file for writing and immediately close it:
#include <stdio.h>
int main()
{
FILE *file = fopen("asdf.txt", "w");
if (!file)
{
perror("Could not open file");
}
fclose(file);
return 0;
}
Opening a file with "w" (for write mode) "empties" the file so you can start overwriting it; immediately closing it then results in a 0-length file.

The truncate() call in UNIX is simply:
truncate("/some/path/file", 0);

While you can just open and close the file, the truncate call is designed specifically for this use case:
#include <unistd.h> //for truncate
#include <stdio.h> //for perror
int main()
{
if (truncate("/home/fmark/file.txt", 0) == -1){
perror("Could not truncate")
}
return 0;
}
If you already have the file open, you can use that handle with ftruncate:
#include <stdio.h> //for fopen, perror
#include <unistd.h> //for ftruncate
int main()
{
FILE *file = fopen("asdf.txt", "r+");
if (file == NULL) {
perror("could not open file");
}
//do something with the contents of file
if (ftruncate(file, 0) == -1){
perror("Could not truncate")
}
fclose(file);
return 0;
}

truncate(2) is not a portable call. It only conforms to 4.2BSD. While it is found on most *nix type systems, I would say use a POSIX.1 compliant routines which are pretty much guaranteed on most modern environments (including Windows).
so here is a POSIX.1-2000 compliant code snippet:
int truncate_file(const char *name) {
int fd;
fd = open (name, O_TRUNC|O_WRONLY);
if ( fd >= 0 )
close(fd); /* open can return 0 as a valid descriptor */
return fd;
}

For deleting the contents of a fie obviously there is basic method of opening a file in write mode "w" and then close it without doing any changes in it.
FILE *fp = fopen (file_path, "w");
fclose(fp);
this will delete all the data in file as when you open a already existing file using "w" mode the file is deleted and a new file with the same name is opened for writing, this will result into deletion of contents of your file.
BUT there is truncate syscall in UNIX systems, which is specially for the same purpose and pretty easy to use:
truncate (filepath, 0);
if you have already opened your file so either you close your file before doing truncate or use ftruncate
ftruncate (file_path, 0);

Related

write the integer value of a file descriptor to a file

Just testing out file descriptors. My aim is to open up a file stream with fopen and using fprintf write the file descriptors integer value back into the file to see what results im getting.
(I decided using fopen, fprintf etc) as it allowed me to write in variables, write() wouldn't allow it,
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
int main ()
{
FILE *fp;
fp = fopen("wow.txt", "w+");
if (fp < 0)
{
printf("ERROR \n");
}
else
{
printf("we good \n");
}
fprintf(fp, "hi %p \n", fp);
}
Issue i am facing is, if i write %d for the fprintf statement...i get a compiler error. If i write %p, I get the address in RAM.
Is it possible to get the absolute integer value...like "3"
FILE *fp;
is not a file descriptor, it's a file stream pointer and, as such, you need to treat it as a pointer.
A file descriptor is a small integer returned from one of the UNIXy calls like open or creat, while file pointers are sort of a level above that, assuming you're in an environment that even has descriptors.
In those environments, you can generally get at the underlying descriptor with something like:
int fd = fileno (fp);
The following complete program (under CygWin) shows this in action:
#include <stdio.h>
int main (void) {
FILE *fp = fopen ("wow.txt", "w+");
if (fp < 0) {
printf ("ERROR\n");
return 1;
}
fprintf (fp, "fp=%p, fd=%d\n", fp, fileno (fp));
fclose (fp);
return 0;
}
Compiling that with:
gcc -o testprog testprog.c
gives the output:
fp=0x800102a8, fd=3

create text file in /tmp folder in Linux using c language

By using c language I need to create a text file in /tmp directory, but I don't know how to do this. Is there anyone who knows how to create a text file in /tmp folder?
There's mkstemp function for this
Taken from here
#include <stdio.h>
int main ()
{
FILE * pFile;
pFile = fopen ("/tmp/myfile.txt","w");
if (pFile!=NULL)
{
//write
fclose (pFile);
}
return 0;
}
If /tmp/myfile.txt isn't there one will be created.
Here is an example:
char *tmp_file;
char buf[1000];
FILE *fp;
tmp_file = "/tmp/sometext.txt";
fp = fopen( tmp_file, "w" );
if ( fp == NULL ) {
printf("File open error! %s", tmp_file );
}
sprintf( buf, "Hello" );
fputs( buf, fp );
fclose( fp );
#include <stdio.h> // Defines fopen(), fclose(), fprintf(), printf(), etc.
#include <errno.h> // Defines errno
C programs generally start with the 'main()' function.
int main()
{
int rCode=0;
FILE *fp = NULL;
'fp' will be a reference to the file, used to read, write, or close the file.
char *filePath = "/tmp/thefile.txt";
'filePath' is a string that holds the path "/tmp" and the filename "thefile.txt".
The following line attempts to open the file in "write" mode, which (if successful) will cause the file "thefile.txt" to be created in the "/tmp" directory.
fp=fopen(filePath, "w");
Incidently, with the "w" (write) mode specified, it "thefile.txt" already exists in the "/tmp" directory, it will be overwritten.
The following code will print an error if the file could not be created.
if(NULL==fp)
{
rCode=errno;
fprintf(stderr, "fopen() failed. errno[%d]\n", errno);
}
After the file is created, it could be written to here:
fprintf(fp, "This is the content of the text file.\nHave a nice day!\n");
Now, the file can be closed.
if(fp)
fclose(fp);
All done.
return(rCode);
}
Several other people have mentioned that the correct way to do this is to use the mkstemp() function, that is because it will ensure your file has a unique name.
Here is a quick example of how to use it:
//Set file name
char filename[] = "/tmp/tmpfile-XXXXXX";
//Open the file in rw mode, X's replaced with random chars
int fd = mkstemp(filename);
//Write stuff to file...
write(fd, filename, strlen(filename));
//Close the file
close(fd);
//Do whatever else you want here, including opening and closing the file again
//Once you are done delete the temporary file
unlink(filename);
I left out error checking on purpose for clarity.

Linux/ Open directory as a file

I've been reading Brian Kernighan and Dennis Ritchie - The C Programming Language and chapter 8.6 is about directory listing under UNIX OS. They say that everything and even directory is a file. This means that I should be able to open directory as a file? I've tried it using stdio functions and it didn't work. Now, I'm trying it with UNIX system functions. Of course, I'm not using UNIX, I'm using Ubuntu linux. Here is my code:
#include <syscall.h>
#include <fcntl.h>
int main(int argn, char* argv[]) {
int fd;
if (argn!=1) fd=open(argv[1],O_RDONLY,0);
else fd=open(".",O_RDONLY,0);
if (fd==-1) return -1;
char buf[1024];
int n;
while ((n=read(fd,buf,1024))>0)
write(1,buf,n);
close (fd);
return 0;
}
This writes nothing even when argn is 1 (no parameters) and I'm trying to read current directory.
Any ideas/explanations? :)
Files are also called regular files to distinguish them from special files.
Directory or not a regular file. The most common special file is the directory. The layout of a directory file is defined by the filesystem used.
So use opendir to open diretory.
Nachiket's answer is correct (as indeed is sujin) but they don't clear up the mystery as to why open works and not read. Out of curiosity I made some changes to the given code to find out exactly what was going on.
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
int main(int argc, char* argv[]) {
int fd = -1;
if (argc!=1) fd=open(argv[1],O_RDONLY,0);
else fd=open(".",O_RDONLY,0);
if (fd < 0){
perror("file open");
printf("error on open = %d", errno);
return -1;
}
printf("file descriptor is %d\n", fd);
char buf[1024];
int n;
if ((n=read(fd,buf,1024))>0){
write(1,buf,n);
}
else {
printf("n = %d\n", n);
if (n < 0) {
printf("read failure %d\n", errno);
perror("cannot read");
}
}
close (fd);
return 0;
}
The result of compiling and running this:
file descriptor is 3
n = -1
read failure 21
cannot read: Is a directory
That settles it, though I'd have expected open to fail, since the correct system function for opening directories is opendir().
Though everything in unix is a file (directory also) but still filetype is concept is present in unix and applicable to all files.
there are file types like regular file,directory etc and certain operations and functions are allowed/present for every file type.
In your case readdir is applicable for reading contents of directory.
If you want to see the files in a directory you have to use the opendir and readdir functions.
K&R were correct for the original UNIX. I remember doing it back when UNIX file systems had a 14 character length limit for filenames. The opendir(), readdir(), ... stuff happened about the time that longer file names became common (around 1990?)

Won't create txt file C program

This is my code
#include <stdio.h>
int main()
{
FILE *file;
file = fopen("file.txt","a+");
fprintf(file,"%s","test :)");
fclose(file);
return 0;
}
Don't understand why it won't create a txt file
help
Please try perror to check if you have permission to write to the file or not. That is the problem most of the time. Add this after fopen
if (!file)
perror("fopen");
You need to check for errors in your program. fopen() can fail for a variety of reasons. We can either inspect errno, or use perror / strerror to print a useful message.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *file = fopen("file.txt","a+");
if (file == NULL) {
perror("Failed to open the file");
exit(-1);
}
fprintf(file,"%s","test :)");
fclose(file);
return 0;
}
For example, if a file exists in the current directory, but is owned by a different user:
[8:40am][wlynch#watermelon /tmp] ./foo
Failed to open the file: Permission denied
Create a file if one doesn't exist - C
here are answers...The one that's under the marked one worked for me on my s.o. The way you are trying to do doesn't work on windows, but works on linux. Sorry for saying what I said before...Both operating systems have their bright and not so bright side.

File reading synchronously in Linux C

Please see below code.
#include < stdio.h >
#include < fcntl.h >
#include < stdlib.h >
#include < string.h >
int main(int argc,char **argv,char **envp)
{
int fd;
size_t sz;
char filebuffer[1024];
int loop;
fd=open("sample",O_RDONLY);
if(fd==-1)
{
perror("");
exit(1);
}
loop=0;
while(++loop<300)
{
lseek(fd,0,SEEK_SET);
memset(filebuffer,0,1024);
sz=read(fd,filebuffer,1024);
printf("%d.sz=%zd\t%s\n",loop,sz,filebuffer);
sleep(1);
}
close(fd);
return 0;
}
In this code, I am able to read file. But when I am changing file (reading file "sample") at the same time during reading. Then I am not able to read the changed file. I tried O_SYNC flag too. but still, it is not working, but O_DIRECT is undefined error is coming up. How can I ensure that I am able to read changes? Second thing, but I observed, if I close and open the file reading, then I am able to read changed file.
Question:
How can I read changed file without closing and opening?
I think that you're asking the following question:
I have a program which opens a file called sample and repeatedly reads the first block of that file. That works fine. However, if I edit the file sample, for example with a text editor, then my program does not see the changes, although it will if it closes and reopens the file. How can I see the changes without closing and reopening the file?
If that's your question, then the answer is:
Sorry, you cannot, because the text editor does not modify the file. It creates a new file with the old name.
In Unix, once you open a file, it will not actually get deleted, even if its name is unlinked. If another program "deletes" the file and then creates a new file with the same name, the file you have open is no longer accessible to any other program, but it is still the same file and it will not get deleted until you close it.
Most Unix text utilities, even the ones which claim to work "in-place" (such as sed -i) really do not modify files. That includes text editors. So your program doesn't see changes in the file because the file is not changing; the name has been given to a new file.
So the only way to deal with this is to close and reopen the file. When you reopen, you will be opening the new file with the old name.
The reason for not getting updated data in file could be sync time in filesystem.
I suggest fflush() after writing in to file. This makes your cache data to be written in file.
Related discussions.
Small file not committed to disk for over a minute
Is fwrite non-blocking?
This is an adaptation of your code. It forks to create two processes. The child contains your code, substantially unchanged (different error message, file name variable, and more care with printing the filebuffer which is not null terminated). The parent writes characters (the same character, over and over) to the file.
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static char const filename[] = "sample";
int main(void)
{
int fd;
size_t sz;
char filebuffer[1024];
int loop;
switch (fork())
{
case -1:
fprintf(stderr, "Failed to fork\n");
break;
case 0:
sleep(1);
fd = open(filename, O_RDONLY);
if (fd == -1)
{
fprintf(stderr, "Failed to open file %s for reading\n", filename);
exit(1);
}
loop = 0;
while (++loop < 300)
{
lseek(fd, 0, SEEK_SET);
memset(filebuffer, 0, 1024);
sz = read(fd, filebuffer, 1024);
printf("%d.sz=%zd\t%.*s\n", loop, sz, (int)sz, filebuffer);
sleep(1);
}
close(fd);
break;
default:
fd = open(filename, O_WRONLY|O_CREAT, 0644);
if (fd == -1)
{
fprintf(stderr, "Failed to create file %s for writing\n", filename);
exit(1);
}
for (loop = 0; loop < 256; loop++)
{
memset(filebuffer, (loop % 64) + 33, sizeof(filebuffer));
lseek(fd, 0L, SEEK_SET);
write(fd, filebuffer, sizeof(filebuffer));
sleep(1);
}
close(fd);
break;
}
return 0;
}
Example output:
1.sz=1024 """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
2.sz=1024 ################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
3.sz=1024 ################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
4.sz=1024 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%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&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
6.sz=1024 ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
7.sz=1024 ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
8.sz=1024 ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
9.sz=1024 ****************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************
As you can see, the processes run asynchronously, so the data in the file does not always change between reads, but the process is seeing the changes.
Try running this on your computer. It should work. (Sample output from Mac OS X 10.8.5.) If it doesn't, you'll need to identify which file system type you have, but I don't think it'll be a problem.

Resources