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.
Related
How can I check if a text file has something written or not. I tried:
LOGIC checkfile(char * filename)
{
FILE *pf;
pf=fopen(filename,"wt");
fseek(pf,0,SEEK_END);
if(ftell(pf)==0)
printf("empty");
}
This function returns empty everytime, even in my text file I have few words or numbers written.
The problem is that you opened the file for writing. When you do that, everything in the file is lost, and the length of the file is truncated to 0.
So you need to open the file for reading. And the easiest way to see if the file is empty is to try to read the first character with fgetc. If fgetc returns EOF, then the file is empty.
First of all: DO NOT OPEN THE FILE FOR WRITING!
second: for knowing about file status in C you can use fstat which is in sys headear file!
You can use struct stat for using this function
here is a simple example:
#include <sys/stat.h>
int main(void)
{
int fields = 0;
int size = 0;
// Open the file test.txt through open()
// Note that since the call to open directly gives
// integer file descriptor so we used open here.
// One can also use fopen() that returns FILE*
// object. Use fileno() in that case to convert
// FILE* object into the integer file descriptor
if(fields = open(file_path, "r")){
struct stat buf;
fstat(fields, &buf);
size = (int)buf.st_size;
}
printf("size of file is %d", size);
return 0;
}
Note: I just include a header file that related to fstat. You can add other header files yourself
What about using fscanf to read the file, and check if something was actually read?
FILE *fp;
char buff[255] = "";
fp = fopen(filename, "r");
fscanf(fp, "%s", buff);
if (!*buff)
printf("Empty\n");
else
printf("%s\n", buff);
fclose(fp);
I am currently writting a program on Linux to get the current CPU usage from /proc/stat and print in to a .txt file. However, whilst writting to the file, I am unable to print a new line, and the output prints OVER the old one...
I would like to print the new line under the previous one, but using the "\n" or "\r" characters didn't work.
The code is here:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void checker();
int main(){
long double a[4], b[4], loadavg;
FILE *fp;
char dump[50];
for(;;){
fp = fopen("/proc/stat","r");
checker();
fscanf(fp,"%*s %Lf %Lf %Lf %Lf",&a[0],&a[1],&a[2],&a[3]);
fclose(fp);
sleep(1);
fp = fopen("/proc/stat","r");
checker();
fscanf(fp,"%*s %Lf %Lf %Lf %Lf",&b[0],&b[1],&b[2],&b[3]);
fclose(fp);
fp = fopen("CPU_log.txt", "w");
checker();
loadavg = ((b[0]+b[1]+b[2]) - (a[0]+a[1]+a[2])) / ((b[0]+b[1]+b[2]+b[3]) - (a[0]+a[1]+a[2]+a[3]));
fprintf(fp, "Current CPU Usage is: %Lf\r\n", loadavg);
fclose(fp);
}
return 0;
}
void checker(){
FILE *fp;
if (fp == NULL){
printf("Error opening file!\n");
exit(1);
}
}
It seems that you need to append new data to existent file (i.e. do not overwrite) instead of creating of empty file each time. Try this:
fp = fopen("CPU_log.txt", "a");
Second argument "a" means "append":
Open file for output at the end of a file. Output operations always write data at the end of the file, expanding it. Repositioning operations (fseek, fsetpos, rewind) are ignored. The file is created if it does not exist.
Also it seems reasanoble to modify your function checker:
void checker(FILE *fp) {
if (fp == NULL){
perror("The following error occurred");
exit(EXIT_FAILURE);
}
}
Inside for loop, You are opening CPU_log.txt file in write mode.
fp = fopen("CPU_log.txt", "w");
Mode w will truncate the file to zero length or create file for writing.
Open file in append mode. This will not overwrite the contents.
fp = fopen("CPU_log.txt", "a");
You need to open the files outside the for()-Loop, otherwise, your file is overwritten continuosly. Or you need to open your file with "a" instead of "w", which appends to the file instead of throwing everything away.
Besides, what is %Lf supposed to do? (Should be %f!)
I am new to C, I am just trying to read a simple text file I created in C. I made this file by clicking new -> empty file -> saving it to my desired location and then adding the file extension (.txt) the text file holds a sample sudoku board and the full file name is sudokuchar.txt.
The code I have to read from the file and print it is:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fpointer = fopen("sudokuchar.txt", "r");
char input[100];
while(fgets(input,100,fpointer))
{
printf("%s",input);
}
fclose(fpointer);
}
so when i compile the program does not print anything and returns -1. I assume something is wrong with the file i am trying to read from?? if some one could help it would be greatly appreciated.
Always check the return values of fopen and other standard library calls. It's most likely that your file doesn't exist. You can make a nice user friendly error message using errno, just make sure to include errno.h. Overall, your code should work, but you NEED to check the return values of things, because fopen returns NULL if it can't find the file.
FILE *fpointer = fopen("sudokuchar.txt", "r");
if(fpointer == NULL) {
fprintf(stderr, "Error: [Errno %d]: %s\n",
errno, strerror(errno));
return 1;
}
It is advisable to check what file pointer returns. If file pointer returns 0 or NULL then File pointer is unable to point to the file name you had provided. Also you can use this
File *fp = fopen(file name with full path (i.e. /home/chex/read.txt),"r")
Check man fopen
FILE *fopen(const char *path, const char *mode);
I am working through the excellent The C Programming Language at the moment, and have got stuck while trying to open and read a file. The program compiles, but seg faults on execution:
$ ./a.out
Segmentation fault
Here is the code:
#include <stdio.h>
main()
{
FILE *fp;
fp=fopen("/home/c-sandbox/index.html", "r");
fprintf(fp, "Testing...\n");
fclose(fp);
}
Note that the path points to a real file containing the string "hello, world".
Any ideas on where I am going wrong?
Make sure fp is not NULL before trying to write to it. For example:
if(fp == NULL)
{
fprintf(stderr, "Cannot open file\n");
return EXIT_FAILURE; // defined in stdlib.h
}
You need to open the file with something other than "r", which only allows file reading. Read the man page for fopen to find out which mode would work the best for you. Example:
"w" - Truncate to zero length or create file for writing.
"a" - Append; open or create file for writing at end-of-file.
You opened the file for reading only, and are attempting to write to it.
Use "a" if you want to append to the end of the existing file.
Edit: As others have noted, you're also not checking to see if the file was opened. fopen will return NULL if it fails and set the global variable errno to a value that indicates why it failed. You can get a human-readable explanation using strerror(errno)
if( fp == NULL ) {
printf( "Error opening file: %s\n", strerror( errno ) );
}
You are opening it in readonly mode! Need to use w or a for writing/appending to the file :)
fopen("/home/c-sandbox/index.html", "w");
You should check that fopen does not return NULL. I suspect it is returning NULL and either the fprintf and/or fclose calls are getting messed up.
#include <stdio.h>
main()
{
FILE *fp;
fp=fopen("/home/c-sandbox/index.html", "r");
if(!fp)
{
perror ("The following error occurred");
return ;
}
fgets(line,len,fp);
printf("%s",line);
fclose(fp);
fp=fopen("/home/c-sandbox/index.html", "a");
if(!fp)
{
perror ("The following error occurred");
return ;
}
fprintf(fp, "Testing...\n");
fclose(fp)
}
for reading "hello, world" string present in file.
after reading write to the same file "Testing..."
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);