C ++ fopen () - C ++ standarta bibliotēka

Funkcija fopen () C ++ atver noteiktu failu noteiktā režīmā.

fopen () prototips

 FILE * fopen (const char * faila nosaukums, const char * režīms);

fopen()Funkcija aizņem divus argumentus un atgriež failu plūsma, kas saistīta ar šo failu ar argumentu filename norādīto.

Tas ir definēts galvenes failā.

Dažādi failu piekļuves režīma veidi ir šādi:

Failu piekļuves režīms Interpretācija Ja fails pastāv Ja fails nepastāv
"r" Atver failu lasīšanas režīmā Lasīt no sākuma Kļūda
"w" Atver failu rakstīšanas režīmā Dzēst visu saturu Izveidot jaunu failu
"a" Atver failu pievienošanas režīmā Sāciet rakstīt no beigām Izveidot jaunu failu
"r +" Atver failu lasīšanas un rakstīšanas režīmā Lasīt no sākuma Kļūda
"w +" Atver failu lasīšanas un rakstīšanas režīmā Dzēst visu saturu Izveidot jaunu failu
"a +" Atver failu lasīšanas un rakstīšanas režīmā Sāciet rakstīt no beigām Izveidot jaunu failu

fopen () parametri

  • faila nosaukums: Virknes rādītājs, kas satur atvērtā faila nosaukumu.
  • režīms: rādītājs virknei, kas norāda režīmu, kurā fails tiek atvērts.

fopen () Atgriešanās vērtība

  • Ja tas izdosies, fopen()funkcija atgriež rādītāju objektam FILE, kas kontrolē atvērto failu straumi.
  • Neveiksmes gadījumā tas atgriež nulles rādītāju.

1. piemērs: faila atvēršana rakstīšanas režīmā, izmantojot 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".

Interesanti raksti...