By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,942 Members | 1,165 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,942 IT Pros & Developers. It's quick & easy.

(part 27) Han from China answers your C questions

P: n/a
fread breaks file descriptors opened in "w" mode.
My problem is that the FILE* I want do parse has been fopen'ed far away
from where I am and I don't know in which MODE my FILE* has been opened.
And additionally, my FILE* may not be a regular file, but a continuous
stream (pipe), in which case it is not rewindable.
...
- given a FILE *, is there a better way to guess in which mode it has been
opened than attempting to read or write it and look at errors ?
- given a FILE *, is there a better way to guess if it can be sought than
attempting a fseek on it ?
Yes, once you break out of ANSI/ISO C, all things are possible.

You have posted an on-topic question to comp.lang.c. See version 2.0 of my topicality
FAQ if anyone should tell you otherwise.
Search: "Han from China's comp.lang.c topicality FAQ (version 2.0)"

I have written some code for you to study and have given you a
demonstration below it. You may want to include full error-checking.

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>

void
PreParsing(FILE *my_file)
{
int fd, fl;
struct stat st;

// if (!my_file) { ... }
fd = fileno(my_file);
fl = fcntl(fd, F_GETFL, 0);
switch(fl & O_ACCMODE) {
case O_RDONLY: puts("read-only");
break;
case O_WRONLY: puts("write-only");
break;
case O_RDWR: puts("read-write");
break;
}

if(fl & O_APPEND)
puts("append");

fstat(fd, &st);
#ifdef S_ISREG
if(S_ISREG(st.st_mode)) puts("regular");
#else
if((st.st_mode & S_IFMT) == S_IFREG) puts("regular");
#endif
else
#ifdef S_ISFIFO
if(S_ISFIFO(st.st_mode)) puts("fifo");
#else
if((st.st_mode & S_IFMT) == S_IFIFO) puts("fifo");
#endif

}

int
main(int argc, char **argv)
{
FILE *file;

if(argc == 3) {
file = fopen(argv[1], argv[2]);
if(file)
PreParsing(file);
}

return 0;
}

$ echo test test
$ ./clc test r
read-only
regular
$ ./clc test w
write-only
regular
$ ./clc test a
write-only
append
regular
$ ./clc test a+
read-write
append
regular
$ mkfifo pipe
$ ./clc pipe r+
read-write
fifo
$ ./clc pipe r & #blocks until writer
$ ./clc pipe w
read-only
write-only
fifo
fifo

Yours,
Han from China

Il mittente di questo messaggio|The sender address of this
non corrisponde ad un utente |message is not related to a real
reale ma all'indirizzo fittizio|person but to a fake address of an
di un sistema anonimizzatore |anonymous system
Per maggiori informazioni |For more info
https://www.mixmaster.it

Nov 18 '08 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.