C fopen vs aberto
Pergunta
Existe alguma razão (exceto os sintáticos) que você deseja usar
FILE *fdopen(int fd, const char *mode);
ou
FILE *fopen(const char *path, const char *mode);
ao invés de
int open(const char *pathname, int flags, mode_t mode);
Ao usar C em um ambiente Linux?
Solução
Primeiro, não há motivo particularmente bom para usar fdopen
E se fopen
é uma opção e open
é a outra escolha possível. Você não deveria ter usado open
Para abrir o arquivo em primeiro lugar, se você quiser um FILE *
. Então, incluindo fdopen
Nessa lista está incorreta e confusa, porque não é muito parecida com os outros. Vou agora ir para ignorá -lo porque a distinção importante aqui está entre um padrão C FILE *
e um descritor de arquivo específico do OS.
Existem quatro razões principais para usar fopen
ao invés de open
.
fopen
fornece a você com io de io que pode ser muito mais rápido do que o que você está fazendoopen
.fopen
A tradução final da linha se o arquivo não for aberto no modo binário, o que pode ser muito útil se o seu programa for portado para um ambiente não unix.- UMA
FILE *
dá a você a capacidade de usarfscanf
e outras funções do stdio. - Seu código pode um dia precisar ser portado para outra plataforma que suporta apenas Ansi c e não suporta o
open
função.
Na minha opinião fscanf
é tão fraco que você inevitavelmente acaba jogando isso em favor de algo mais útil.
E a maioria das plataformas que suportam C têm um open
função.
Isso deixa a questão tampão. Em lugares onde você está lendo ou escrevendo principalmente um arquivo sequencialmente, o suporte ao buffer é realmente útil e uma grande melhoria de velocidade. Mas isso pode levar a alguns problemas interessantes nos quais os dados não acabam no arquivo quando você espera que ele esteja lá. Você tem que se lembrar de fclose
ou fflush
nos momentos apropriados.
Se você está fazendo (também conhecido como fsetpos
ou fseek
o segundo dos quais é um pouco mais complicado de usar de maneira compatível com padrões), a utilidade do buffer diminui rapidamente.
Claro, meu preconceito é que eu tendem a trabalhar muito com soquetes, e aí o fato de que você realmente quer fazer IO não bloqueando (o que FILE *
Falha totalmente em apoiar de maneira razoável) sem buffer e geralmente tem requisitos complexos de análise realmente coloram minhas percepções.
Outras dicas
open()
é uma chamada de sistema operacional de baixo nível. fdopen()
Converte um descritor de arquivo no nível do OS no nível mais alto-abstração de arquivos do idioma C. fopen()
chamadas open()
em segundo plano e fornece um ponteiro de arquivo diretamente.
Existem várias vantagens no uso de objetos de arquivo, bastante descritores de arquivos brutos, que incluem maior facilidade de uso, mas também outras vantagens técnicas, como buffer interno. Especialmente o buffer geralmente resulta em uma vantagem considerável de desempenho.
fopen vs open in C
1) fopen
is a library function while open
is a system call.
2) fopen
provides buffered IO which is faster compare to open
which is non buffered.
3) fopen
is portable while open
not portable (open is environment specific).
4) fopen
returns a pointer to a FILE structure(FILE *); open
returns an integer that identifies the file.
5) A FILE *
gives you the ability to use fscanf and other stdio functions.
If you have a FILE *
, you can use functions like fscanf
, fprintf
and fgets
etc. If you have just the file descriptor, you have limited (but likely faster) input and output routines read
, write
etc.
Unless you're part of the 0.1% of applications where using open
is an actual performance benefit, there really is no good reason not to use fopen
. As far as fdopen
is concerned, if you aren't playing with file descriptors, you don't need that call.
Stick with fopen
and its family of methods (fwrite
, fread
, fprintf
, et al) and you'll be very satisfied. Just as importantly, other programmers will be satisfied with your code.
Using open, read, write means you have to worry about signal interaptions.
If the call was interrupted by a signal handler the functions will return -1 and set errno to EINTR.
So the proper way to close a file would be
while (retval = close(fd), retval == -1 && ernno == EINTR) ;
open() will be called at the end of each of the fopen() family functions. open() is a system call and fopen() are provided by libraries as a wrapper functions for user easy of use
open()
is a system call and specific to Unix-based systems and it returns a file descriptor. You can write to a file descriptor using write()
which is another system call.
fopen()
is an ANSI C function call which returns a file pointer and it is portable to other OSes. We can write to a file pointer using fprintf
.
In Unix:
You can get a file pointer from the file descriptor using:
fP = fdopen(fD, "a");
You can get a file descriptor from the file pointer using:
fD = fileno (fP);
Depends also on what flags are required to open. With respect to usage for writing and reading (and portability) f* should be used, as argued above.
But if basically want to specify more than standard flags (like rw and append flags), you will have to use a platform specific API (like POSIX open) or a library that abstracts these details. The C-standard does not have any such flags.
For example you might want to open a file, only if it exits. If you don't specify the create flag the file must exist. If you add exclusive to create, it will only create the file if it does not exist. There are many more.
For example on Linux systems there is a LED interface exposed through sysfs. It exposes the brightness of the led through a file. Writing or reading a number as a string ranging from 0-255. Of course you don't want to create that file and only write to it if it exists. The cool thing now: Use fdopen to read/write this file using the standard calls.
I changed to open() from fopen() for my application, because fopen was causing double reads every time I ran fopen fgetc . Double reads were disruptive of what I was trying to accomplish. open() just seems to do what you ask of it.
opening a file using fopen
before we can read(or write) information from (to) a file on a disk we must open the file. to open the file we have called the function fopen.
1.firstly it searches on the disk the file to be opened.
2.then it loads the file from the disk into a place in memory called buffer.
3.it sets up a character pointer that points to the first character of the buffer.
this the way of behaviour of fopen function
there are some causes while buffering process,it may timedout. so while comparing fopen(high level i/o) to open (low level i/o) system call , and it is a faster more appropriate than fopen.