Can't open 2 FILE * - c

I was working on a program in C for Raspberry PI development, and I've been getting this weird bug.
I honestly have no clue regarding its origins. The program is very simple so far.
#include <bcm2835.h>
#include <time.h>
#include <sys/time.h>
#include <stdint.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/types.h>
#include <linux/spi/spidev.h>
int main(int argc, char *argv[])
{
FILE *file;
FILE *file2;
FILE *peak1;
FILE *peak2;
file = fopen("input0.txt", "a+");
file2 = fopen("input1.txt", "a+");
peak1=fopen("peak1.txt", "a+");
peak2=fopen("peak2.txt", "a+");
fprintf(file, "%s\n", "HELLO!");
fprintf(peak1, "%s\n", "HELLO!");
}
Bug:-
When I run the program and check the outputs to the files, Only 'input0.txt' has "HELLO!" written where as 'peak1.txt' has nothing.
I can write to the first two files file and file2, but cannot write to the second two files peak1 and peak2.
I have tried writing multiple things but to no avail. What could be the problem?
Thanks!

You forgot to call fclose(FILE *) at the end. Calling int fclose(FILE *fp); will ensure the file descriptor is properly disposed of and output buffers flushed so the data written to the file will be present in the file on disk.
From: IEEE Std 1003.1, 2004 Edition:
int fclose(FILE *stream);
The fclose() function shall cause the stream pointed to by stream to
be flushed and the associated file to be closed. Any unwritten
buffered data for the stream shall be written to the file; any unread
buffered data shall be discarded. Whether or not the call succeeds,
the stream shall be disassociated from the file and any buffer set by
the setbuf() or setvbuf() function shall be disassociated from the
stream. If the associated buffer was automatically allocated, it shall
be deallocated.

You need to call fclose(FILE *) at the end of your code.
The C library function int fclose(FILE *stream) closes the stream. All buffers are flushed.

Related

Instant write buffer to stdout

Is possible to write a large block of text into stdout all at once.
For instance, I get a 50kb text file and put it into story.txt. I am curious if I can dump the contents of this file into stdout without the user noticing any text slowly coming in. One moment there is no text, next the whole buffer is flushed into stdout.
I was trying to do it with the following code but no matter what buffering mode I set it didn't manage to write the file all at once, only in parts.
/* dumps a lot of text at once */
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
char story[100000];
char buffer[100000];
int main(int argc, char **argv)
{
FILE *handle = fopen("coolstory.txt", "r");
size_t n = fread(&story[0], 1, 100000, handle);
fclose(handle);
/* try to flush all at once... */
fclose(stdout);
freopen("/dev/tty", "w", stdout);
setvbuf(stdout, &buffer[0], _IOFBF, 100000);
fwrite(story, n, 1, stdout);
fflush(stdout);
printf("\nread %u bytes.\n", n);
return 0;
}
The reopen part was me wondering if setvbuf/flush would behave differently if I called them right after the stdout was opened. Unfortunately it did nothing.
I just want to know whether it is possible, and if not, why.
I'm on ubuntu linux 14.04.
Note: it is usually a bad idea to #include header files that are not used.
I ran this version of the code:
/* dumps a lot of text at once */
//#include <unistd.h>
#include <stdio.h>
//#include <stdlib.h>
//#include <fcntl.h>
//#include <string.h>
char story[100000];
int main( void )
{
FILE *handle = fopen("value_chainLength.txt", "r");
size_t n = fread(story, 1, 100000, handle);
fclose(handle);
fwrite(story, n, 1, stdout);
fflush(stdout);
printf("\nread %lu bytes.\n", (long unsigned)n);
return 0;
}
on a 46550749 byte text file
The output was done on a terminal almost as fast as I could press and release the 'enter' key.
the last line output was:
read 100000 bytes.
I did notice ever so slight a hesitation before printing the last line, all the lines before that point were practically instantaneous.

Setting Immutable Flag using ioctl() in C

I have attempted to make a script that creates a file and then sets it as immutable similar to the chattr +i command for linux. The script compiles (with gcc), runs and the file is created. However the file itself is not immutable and can be removed with a simple rm -f. I have attempted to stacktrace where chattr is called and I found a function called ioctl. I then used what little information I could gather and came up with what I have below. I narrowed it down from ext2_fs.h but it just doesn't seem to work. I've clearly overlooked something.
Updates to previous entry: Compiles but returns -1 on ioctl() function. Bad address shown with perror().
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <linux/fs.h>
int main()
{
FILE *fp;
char shovel[16] = "I have a shovel!";
fp = fopen("/shovel.txt", "w+");
fwrite(shovel, sizeof(shovel[0]), sizeof(shovel)/sizeof(shovel[0]), fp);
ioctl(fileno(fp), FS_IOC_SETFLAGS, 0x00000010);
fclose(fp);
}
Any help appreciated.
You are using the right ioctl command, but you're passing it the wrong arguments.
The manpage for ioctl_list(2) shows that FS_IOC_SETFLAGS expects to receive a pointer to int (an int *), yet you're passing it an integer literal (hence the Bad Address error).
The fact that you don't to any error checking whatsoever is also not helping.
The correct flag to pass to FS_IOC_SETFLAGS is a pointer holding the value EXT2_IMMUTABLE_FL, which is defined in ext2fs/ext2_fs.h (some older / different Linux distributions seem to have it under linux/ext2_fs.h), so you'll need to #include <ext2fs/etx2_fs.h>. Make sure to install e2fslibs-dev (and probably you'll need linux-headers too).
This code is working:
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <linux/fs.h>
#include <ext2fs/ext2_fs.h>
int main()
{
FILE *fp;
char shovel[16] = "I have a shovel!";
if ((fp = fopen("shovel.txt", "w+")) == NULL) {
perror("fopen(3) error");
exit(EXIT_FAILURE);
}
fwrite(shovel, sizeof(shovel[0]), sizeof(shovel)/sizeof(shovel[0]), fp);
int val = EXT2_IMMUTABLE_FL;
if (ioctl(fileno(fp), FS_IOC_SETFLAGS, &val) < 0)
perror("ioctl(2) error");
fclose(fp);
return 0;
}
Remember to run this as root.
UPDATE:
As Giuseppe Guerrini suggests in his answer, you might want to use FS_IMMUTABLE_FL instead, and you won't need to include ext2_fs.h:
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <linux/fs.h>
int main()
{
FILE *fp;
char shovel[16] = "I have a shovel!";
if ((fp = fopen("shovel.txt", "w+")) == NULL) {
perror("fopen(3) error");
exit(EXIT_FAILURE);
}
fwrite(shovel, sizeof(shovel[0]), sizeof(shovel)/sizeof(shovel[0]), fp);
int val = FS_IMMUTABLE_FL;
if (ioctl(fileno(fp), FS_IOC_SETFLAGS, &val) < 0)
perror("ioctl(2) error");
fclose(fp);
return 0;
}
The main problem is that the ioctl wants a pointer to the mask, not a direct constant. You have to define a int variable, store the mask (0x10) in it and pass its address as third argument of ioctl.
Also, I'd add some hints:
other programs to change attributes are used to use low-level I/O directly (open, close...). Also, the file is usually opened with O_RDONLY.
Use FS_IMMUTABLE_FL istead the raw constant.
Get the current attribute mask first (FS_IOC_SETFLAGS) and mask it with the new flag, so other settings are not lost by the service.

Call to fdopendir() corrupts file descriptor

I stumbled upon a problem in a program I was working on. The following reproduces my issue:
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
int main(int argc, char *argv[])
{
int fd, ret_fd;
DIR *dirp;
fd = open("./", O_RDONLY);
#if 1
if ((dirp = fdopendir(fd)) == NULL) {
perror("dirp");
return 1;
}
closedir(dirp);
#endif
ret_fd = openat(fd, "Makefile", O_RDONLY);
if (ret_fd == -1) {
perror("ret_fd");
return 1;
}
return 0;
}
Basically, the call to openat(), which has been preceeded by fdopendir(), fails with: Bad file descriptor. However, this does not happen if fdopendir() is omitted.
I know that fdopendir() makes internal use of the file descriptor, but shouldn't it revert any changes to it after calling closedir()?
What can I do to prevent openat() from failing in this case?
The POSIX description of fdopendir() says:
Upon calling closedir() the file descriptor shall be closed.
So the descriptor is likely to be closed by the time you call openat().
And this is from a typical Linux man page for fdopendir():
After a successful call to fdopendir(), fd is used internally by the
implementation, and should not otherwise be used by the application.

libevent: raise event on file change

I have the following code:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <event.h>
void fd_cb(int fd,short event,void *arg){
printf("changed\n");
}
int main(int argc, const char* argv[]){
struct event eoh_ev;
FILE *fp;
int fd;
fp=fopen("/var/log/syslog","rw");
fd=fileno(fp);
event_init();
event_set(&eoh_ev,fd,EV_READ|EV_WRITE,fd_cb,NULL);
event_add(&eoh_ev,NULL);
event_dispatch();
return 0;
}
As you can see, I'm trying to call fd_cb(...) when something is written to /var/log/syslog.
The problem is, "changed" never gets printed!
I'm running the code as root.
Many thanks in advance,
Libevent is designed to work on the same file descriptors that poll or select support. Those system calls are not designed to check for file change events. They are designed to return when a file descriptor can be read or written without blocking, something that isn't very meaningful for regular files (reads and writes to regular files either never block or can always block, depending on how you look at it). In other words - libevent on file descriptors other than sockets, pipes and fifo:s will not work.
There are other mechanisms for checking if a file has changed, but those are not portable.

Distinguishing a pipe from a file in Unix

Given a FILE*, is it possible to determine the underlying type? That is, is there a function that will tell me if the FILE* is a pipe or a socket or a regular on-disk file?
There's a fstat(2) function.
NAME
stat, fstat, lstat - get file status
SYNOPSIS
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int fstat(int fd, struct stat *buf);
You can get the fd by calling fileno(3).
Then you can call S_ISFIFO(buf) to figure it out.
Use the fstat() function. However, you'll need to use the fileno() macro to get the file descriptor from file FILE struct.
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
FILE *fp = fopen(path, "r");
int fd = fileno(fp);
struct stat statbuf;
fstat(fd, &statbuf);
/* a decoding case statement would be good here */
printf("%s is file type %08o\n", path, (statbuf.st_mode & 0777000);

Resources