C ++ fopen () - C ++ Standardbibliotek

Funktionen fopen () i C ++ öppnar en viss fil i ett visst läge.

fopen () prototyp

 FIL * fopen (const char * filnamn, const char * mode);

Den fopen()funktionen tar två argument och returnerar en fil ström i samband med att filen som anges av argumentet filnamn.

Det definieras i rubrikfilen.

Olika typer av filåtkomstläge är följande:

Filåtkomstläge Tolkning Om filen finns Om filen inte finns
"r" Öppnar filen i läsläge Läs från början Fel
"w" Öppnar filen i skrivläge Radera allt innehåll Skapa ny fil
"a" Öppnar filen i append-läge Börja skriva från slutet Skapa ny fil
"r +" Öppnar filen i läs- och skrivläge Läs från början Fel
"w +" Öppnar filen i läs- och skrivläge Radera allt innehåll Skapa ny fil
"a +" Öppnar filen i läs- och skrivläge Börja skriva från slutet Skapa ny fil

fopen () Parametrar

  • filnamn: pekare till strängen som innehåller namnet på filen som ska öppnas.
  • mode: pekare till strängen som anger vilket läge filen öppnas i.

fopen () Returvärde

  • Om det lyckas fopen()returnerar funktionen en pekare till FILE-objektet som styr den öppnade filströmmen.
  • Vid misslyckande returnerar den en nollpekare.

Exempel 1: Öppna en fil i skrivläge med 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".

Intressanta artiklar...