Check if a file is empty or not - c

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);

Related

can't access a place in memory

I'm trying to read a binary file of 32 bytes in C, however I'm keep getting "segmentation fault (code dumped)" when I run my program,
it would be great if somebody can help me out by pointing where did I go wrong?.
my code is here below:
int main()
{
char *binary = "/path/to/myfiles/program1.ijvm";
FILE *fp;
char buffer[32];
// Open read-only
fp = fopen(binary, "rb");
// Read 128 bytes into buffer
fread (buffer, sizeof(char), 32, fp);
return 0;
}
It's because of the path. Make sure that "/path/to/myfiles/program1.ijvm" points to an existing file.
You should always check the return value of fopen.
\\Open read-only
fp = fopen(binary, "rb");
if(fp==NULL){
perror("problem opening the file");
exit(EXIT_FAILURE);
}
Notice also that you are reading 32 bytes in your buffer and not 128 as your comment says.
You must check the return result from fopen().
I'm assuming you are getting the segfault in the fread() call because your data file doesn't exist, or couldn't be opened, and you are trying to work on a NULL FILE structure.
See the following safe code:
#include <stdio.h>
#include <stdint.h>
#define SIZE_BUFFER 32
int main()
{
char *binary = "data.txt";
FILE *fp = NULL;
char buffer[SIZE_BUFFER];
// Open read-only
fp = fopen(binary, "rb");
// Read SIZE_BUFFER bytes into buffer
if( fp )
{
printf("Elements read %ld\n", fread (buffer, sizeof(char), SIZE_BUFFER, fp));
fclose(fp);
}
else
{
// Use perror() here to show a text description of what failed and why
perror("Unable to open file: ");
}
return 0;
}
When I execute this code it doesn't crash and will print the number of elements read if the file is opened or it will print "Unable to open file" if the file could not be opened.
As mentioned in the comments you should also close the file being exiting. Another thing you can do is the following:
FILE *fp = fopen(.....);
Instead of declaring and assigning in two separate steps.
There are two possible reasons
The fopen(3) function failed due to some reason, which means fp is NULL, and then you are trying to use the null-pointer in fread(3). This can crash. #OznOg has already given a subtle hint to look into this direction.
If the fopen call is a success (i.e. fp is non-NULL after calling fopen), the code can still crash because you are reading 32 chars into the variable binary, while binary has been initialized with only 30 chars.

fscanf() fclose() or reading file exit and ends program

Below is a part of my code which is having issues with file handling. The file opens fine with fopen but when I try to read or just close the file my program exits without an error. I tried to run this code independently and it works fine. Would really appreciate if someone could help me out which pointing out what I am doing wrong.
int ctrlSend(char *etherPort, uint8_t *inPayload, int payloadLen, int vlanID)
{
char intName [10]; // Interface name from file
int intVlan; // Interface VLAN from file
printf("In ctrlSend\n");
FILE * pFile; // File pointer
pFile = fopen ("vlan.conf","r");
while(!feof(pFile))
{
fscanf(pFile,"%s %d",intName,&intVlan)
printf("In ctrlSend while loop");
}
fclose (pFile);
return 0;
}
UPDATE1: Updated above code
UPDATE2: Alternate code below which has same issue.
int ctrlSend(char *etherPort, uint8_t *inPayload, int payloadLen, int vlanID)
{
printf("In ctrlSend\n");
char intName [10]; // Interface name from file
int intVlan; // Interface VLAN from file
FILE * pFile; // File pointer
pFile = fopen ("vlan.conf","r");
while (fscanf (pFile,"%s %d",intName,&intVlan) == 2)
{
printf("In ctrlSend while loop");
}
fclose (pFile);
return 0;
}
UPDATE3: Seems like the file is not opening, looking into it.
When you do while (!feof ...) you check each time if you have reach the end of the file. However, at no point your advance in the file (fread ?). That means this will never terminate.
Check whether the file exists or not. You should always check whether File pointer is NULL or not after opening the file. I think your program is unable to open the file and you are trying to use the file pointer without checking which is causing undefined behavior.

How to read from a text file I made in C

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);

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.

C: can't write data on file

i want to open a file, write some data on it so i have to use (Fopen) " i can't use open because i need fopen in some other things "
now if i want to write on the file using fwrite it just don't i don't know why this is what i referred to in my code #option1, but if i get the file descriptor and use normal write method everything works fine see #option 2 below.
anyone can help me to make fwrite works ?
char file_data[256] // has some values
int file_size = strlen(file_data);
FILE *file;
file = fopen(MY_FILE_NAME, "w+");
if(!file){//edited
return false;
}
#option 1//this is not working
fwrite(file_data,1,file_size,file);
#end of option 1
#option 2//this works
int fd = fileno(file);
int x = write(fd,file_data,file_size);//
#end of option 1
EDIT
my file_data is something like this
4 bytes is reserved for an integer (required)
200 bytes is reserved for a string (optional)
buffered IO operations use a buffer that is managed by the C lib. Your "problem" is that fwrite is buffered meaning that in order to write to the file you most likely need to flush it with fflush() or just close the file.
First of all:
if(!file < 0 ){
return false;
}
file is either NULL (on failure) or not (on success) - there's no point in testing it against 0 as it's a pointer (therefore, unsigned).
Your fwrite call seems OK, but you should make sure that the amount you're trying to write is correct (is there a null-terminated string inside file_data?).
Another problem you may be facing is that you don't close or flush the file - this may cause some data to remain in the file-buffer and not be written to the disk.
If you want to check the fopen() return value, do like this:
if (file == NULL) return false;
then, if you want to write a string fputs() is preferable, IMHO, because it communicates better that what you're writing is a string.
Since, according to your last edit, you aren't writing ASCII strings, this is what you should code:
#include <stdio.h>
struct String
{
int size;
char data[200];
};
int main()
{
struct String s;
FILE* file = NULL;
file = fopen("filename", "wb+");
memset(&s, '\0', sizeof(s));
strcpy(s.data, "Hello, world!");
s.size = strlen(s.data);
fwrite(&s, 1, sizeof(s), file);
if (!file) return 1;
fclose(file);
}
At first sight, the mistake seems to be at line #2:
int file_size = strlen(file_data);
This only works if there exists a terminal nul character. So file_size must be either provided for example as a function argument or the you must use the full size of the array.
The following should work:
int write_in_my_file(int data_int, const char* data_str)
{
size_t written;
FILE* file = fopen(MY_FILE_NAME, "wb+"); /* SuperJulietta */
if (!file) return false;
written = fwrite(&data_int, sizeof(data_int), 1, file);
if (written == sizeof(data_int))
{
if (opt_str) fputs(opt_str, file);
}
fclose(file);
return written == sizeof(data_int);
}
Note: this code was not compiled, and error handling is partial.
Edit : if you don't close the file, you'll have to call fflush instead.
You have to put a fflush(file); after the fwrite to force the writing of the data or you can also remove the buffer completely by doing a setbuf(file, NULL); after your fopen call.
I think you need to either do fclose(file) or fflush(file). because fopen is buffered IO so It does not write immidiately, so to ensure that file write is done, you need to do this.
I guess your fwrite code is not the problem.
Whenever the first byte in your file_data is \0 then you write nothing. Since the data is not a string, write 256 bytes. This code works:
#include <stdio.h>
#include <string.h>
#define MY_FILE_NAME "sample.bin"
#define SAMPLE_DATA "Content Content"
int main()
{
char file_data[256];
int file_size = sizeof(file_data);
// fill in some sample data
memcpy(file_data, SAMPLE_DATA, sizeof(SAMPLE_DATA));
FILE *file = fopen(MY_FILE_NAME, "w+");
if (file) {
fwrite(file_data, 1, file_size, file);
fclose(file);
}
}
You see, this is your fwrite. I use sizeof instead of strlen to determine the amount of bytes that will be written...
BR
fwrite is used for binary output, so you have to open file with "wb"

Resources