De functie fopen () in C ++ opent een gespecificeerd bestand in een bepaalde modus.
fopen () prototype
FILE * fopen (const char * filename, const char * mode);
De fopen()
functie accepteert twee argumenten en retourneert een bestandsstroom die bij dat bestand hoort, gespecificeerd door het argument bestandsnaam.
Het wordt gedefinieerd in het header-bestand.
De verschillende soorten bestandstoegangsmodi zijn als volgt:
Bestandstoegangsmodus | Interpretatie | Als het bestand bestaat | Als het bestand niet bestaat |
---|---|---|---|
"r" | Opent het bestand in leesmodus | Lees vanaf het begin | Fout |
"w" | Opent het bestand in de schrijfmodus | Wis alle inhoud | Maak een nieuw bestand |
"een" | Opent het bestand in de toevoegmodus | Begin met schrijven vanaf het einde | Maak een nieuw bestand |
"r +" | Opent het bestand in lees- en schrijfmodus | Lees vanaf het begin | Fout |
"w +" | Opent het bestand in lees- en schrijfmodus | Wis alle inhoud | Maak een nieuw bestand |
"a +" | Opent het bestand in lees- en schrijfmodus | Begin met schrijven vanaf het einde | Maak een nieuw bestand |
fopen () Parameters
- filename: Pointer naar de string met de naam van het te openen bestand.
- mode: Pointer naar de tekenreeks die de modus aangeeft waarin het bestand wordt geopend.
fopen () Retourwaarde
- Als dit lukt,
fopen()
retourneert de functie een pointer naar het FILE-object dat de geopende bestandsstroom bestuurt. - Bij een mislukking retourneert het een nul-aanwijzer.
Voorbeeld 1: een bestand openen in de schrijfmodus met fopen ()
#include #include using namespace std; int main() ( int c; FILE *fp; fp = fopen("file.txt", "w"); char str(20) = "Hello World!"; if (fp) ( for(int i=0; i
When you run the program, it will not generate any output but will write "Hello World!" to the file "file.txt".
Example 2: Opening a file in read mode using fopen()
#include using namespace std; int main() ( int c; FILE *fp; fp = fopen("file.txt", "r"); if (fp) ( while ((c = getc(fp)) != EOF) putchar(c); fclose(fp); ) return 0; )
When you run the program, the output will be (Assuming the same file as in Example 1):
Hello World!
Example 3: Opening a file in append mode using fopen()
#include #include using namespace std; int main() ( int c; FILE *fp; fp = fopen("file.txt", "a"); char str(20) = "Hello Again."; if (fp) ( putc('',fp); for(int i=0; i
When you run the program, it will not generate any output but will append "Hello Again" in a newline to the file "file.txt".