C I / O datotek: Odpiranje, branje, pisanje in zapiranje datoteke

V tej vadnici boste izvedeli več o ravnanju z datotekami v C. Naučili se boste ravnati s standardnimi V / I v C z uporabo fprintf (), fscanf (), fread (), fwrite (), fseek () itd. S pomočjo primeri.

Datoteka je vsebnik v računalniških pomnilniških napravah, ki se uporablja za shranjevanje podatkov.

Zakaj so potrebne datoteke?

  • Ko program preneha, se izgubijo celotni podatki. Shranjevanje v datoteko bo ohranilo vaše podatke, tudi če se program konča.
  • Če morate vnesti veliko število podatkov, bo trajalo veliko časa, da jih vnesete.
    Če pa imate datoteko, ki vsebuje vse podatke, lahko z nekaj ukazi v C. enostavno dostopate do njene vsebine.
  • Podatke lahko enostavno premikate iz enega računalnika v drugega brez sprememb.

Vrste datotek

Pri obravnavi datotek morate vedeti dve vrsti datotek:

  1. Besedilne datoteke
  2. Binarne datoteke

1. Besedilne datoteke

Besedilne datoteke so običajne datoteke .txt . Besedilne datoteke lahko preprosto ustvarite s pomočjo preprostih urejevalnikov besedil, kot je Notepad.

Ko odprete te datoteke, boste vso vsebino v datoteki videli kot navadno besedilo. Vsebino lahko enostavno uredite ali izbrišete.

Za vzdrževanje se trudijo najmanj, so lahko berljivi, zagotavljajo najmanj varnosti in zavzemajo več prostora za shranjevanje.

2. Binarne datoteke

Binarne datoteke so večinoma datoteke .bin v vašem računalniku.

Namesto da podatke shranijo v navadnem besedilu, jih shranijo v binarni obliki (0 in 1).

Vsebujejo lahko več podatkov, jih ni mogoče zlahka prebrati in zagotavlja boljšo varnost kot besedilne datoteke.

Datotečne operacije

V C lahko izvedete štiri glavne operacije z datotekami, bodisi besedilno bodisi binarno:

  1. Ustvarjanje nove datoteke
  2. Odpiranje obstoječe datoteke
  3. Zapiranje datoteke
  4. Branje in zapisovanje informacij v datoteko

Delo z datotekami

Pri delu z datotekami morate prijaviti kazalec tipa datoteke. Ta izjava je potrebna za komunikacijo med datoteko in programom.

 FILE *fptr;

Odpiranje datoteke - za ustvarjanje in urejanje

Odpiranje datoteke se izvede s fopen()funkcijo, določeno v stdio.hglavi datoteke.

Sintaksa za odpiranje datoteke v standardnem V / I je:

 ptr = fopen("fileopen","mode"); 

Na primer

 fopen("E:\cprogram\newprogram.txt","w"); fopen("E:\cprogram\oldprogram.bin","rb");
  • Recimo, da datoteka newprogram.txtna lokaciji ne obstaja E:cprogram. Prva funkcija ustvari novo datoteko z imenom newprogram.txtin jo odpre za pisanje v skladu z načinom 'w' .
    Način pisanja vam omogoča ustvarjanje in urejanje (prepisovanje) vsebine datoteke.
  • Zdaj pa predpostavimo, da na mestu oldprogram.binobstaja druga binarna datoteka E:cprogram. Druga funkcija odpre obstoječo datoteko za branje v binarnem načinu 'rb' .
    Način branja omogoča samo branje datoteke, v datoteko ne morete zapisovati.
Načini odpiranja v standardnem V / I
Način Pomen načina Med neobstojem datoteke
r Odprto za branje. Če datoteka ne obstaja, fopen()vrne NULL.
rb Odprto za branje v binarnem načinu. Če datoteka ne obstaja, fopen()vrne NULL.
w Odprto za pisanje. Če datoteka obstaja, se njena vsebina prepiše.
Če datoteka ne obstaja, bo ustvarjena.
wb Odprto za pisanje v binarnem načinu. Če datoteka obstaja, se njena vsebina prepiše.
Če datoteka ne obstaja, bo ustvarjena.
a Odprto za dodajanje.
Podatki se dodajo na konec datoteke.
Če datoteka ne obstaja, bo ustvarjena.
ab Odprto za dodajanje v binarnem načinu.
Podatki se dodajo na konec datoteke.
Če datoteka ne obstaja, bo ustvarjena.
r+ Odprto za branje in pisanje. Če datoteka ne obstaja, fopen()vrne NULL.
rb+ Odprto za branje in pisanje v binarnem načinu. Če datoteka ne obstaja, fopen()vrne NULL.
w+ Odprto za branje in pisanje. Če datoteka obstaja, se njena vsebina prepiše.
Če datoteka ne obstaja, bo ustvarjena.
wb+ Odprto za branje in pisanje v binarnem načinu. Če datoteka obstaja, se njena vsebina prepiše.
Če datoteka ne obstaja, bo ustvarjena.
a+ Odprto za branje in dodajanje. Če datoteka ne obstaja, bo ustvarjena.
ab+ Odprto za branje in dodajanje v binarnem načinu. Če datoteka ne obstaja, bo ustvarjena.

Zapiranje datoteke

Datoteko (besedilno in binarno) je treba po branju / pisanju zapreti.

Zapiranje datoteke se izvede s pomočjo fclose()funkcije.

 fclose(fptr);

Here, fptr is a file pointer associated with the file to be closed.

Reading and writing to a text file

For reading and writing to a text file, we use the functions fprintf() and fscanf().

They are just the file versions of printf() and scanf(). The only difference is that fprint() and fscanf() expects a pointer to the structure FILE.

Example 1: Write to a text file

 #include #include int main() ( int num; FILE *fptr; // use appropriate location if you are using MacOS or Linux fptr = fopen("C:\program.txt","w"); if(fptr == NULL) ( printf("Error!"); exit(1); ) printf("Enter num: "); scanf("%d",&num); fprintf(fptr,"%d",num); fclose(fptr); return 0; ) 

This program takes a number from the user and stores in the file program.txt.

After you compile and run this program, you can see a text file program.txt created in C drive of your computer. When you open the file, you can see the integer you entered.

Example 2: Read from a text file

 #include #include int main() ( int num; FILE *fptr; if ((fptr = fopen("C:\program.txt","r")) == NULL)( printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); ) fscanf(fptr,"%d", &num); printf("Value of n=%d", num); fclose(fptr); return 0; ) 

This program reads the integer present in the program.txt file and prints it onto the screen.

If you successfully created the file from Example 1, running this program will get you the integer you entered.

Other functions like fgetchar(), fputc() etc. can be used in a similar way.

Reading and writing to a binary file

Functions fread() and fwrite() are used for reading from and writing to a file on the disk respectively in case of binary files.

Writing to a binary file

To write into a binary file, you need to use the fwrite() function. The functions take four arguments:

  1. address of data to be written in the disk
  2. size of data to be written in the disk
  3. number of such type of data
  4. pointer to the file where you want to write.
 fwrite(addressData, sizeData, numbersData, pointerToFile);

Example 3: Write to a binary file using fwrite()

 #include #include struct threeNum ( int n1, n2, n3; ); int main() ( int n; struct threeNum num; FILE *fptr; if ((fptr = fopen("C:\program.bin","wb")) == NULL)( printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); ) for(n = 1; n < 5; ++n) ( num.n1 = n; num.n2 = 5*n; num.n3 = 5*n + 1; fwrite(&num, sizeof(struct threeNum), 1, fptr); ) fclose(fptr); return 0; ) 

In this program, we create a new file program.bin in the C drive.

We declare a structure threeNum with three numbers - n1, n2 and n3, and define it in the main function as num.

Now, inside the for loop, we store the value into the file using fwrite().

The first parameter takes the address of num and the second parameter takes the size of the structure threeNum.

Since we're only inserting one instance of num, the third parameter is 1. And, the last parameter *fptr points to the file we're storing the data.

Finally, we close the file.

Reading from a binary file

Function fread() also take 4 arguments similar to the fwrite() function as above.

 fread(addressData, sizeData, numbersData, pointerToFile);

Example 4: Read from a binary file using fread()

 #include #include struct threeNum ( int n1, n2, n3; ); int main() ( int n; struct threeNum num; FILE *fptr; if ((fptr = fopen("C:\program.bin","rb")) == NULL)( printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); ) for(n = 1; n < 5; ++n) ( fread(&num, sizeof(struct threeNum), 1, fptr); printf("n1: %d n2: %d n3: %d", num.n1, num.n2, num.n3); ) fclose(fptr); return 0; ) 

In this program, you read the same file program.bin and loop through the records one by one.

In simple terms, you read one threeNum record of threeNum size from the file pointed by *fptr into the structure num.

You'll get the same records you inserted in Example 3.

Getting data using fseek()

If you have many records inside a file and need to access a record at a specific position, you need to loop through all the records before it to get the record.

This will waste a lot of memory and operation time. An easier way to get to the required data can be achieved using fseek().

As the name suggests, fseek() seeks the cursor to the given record in the file.

Syntax of fseek()

 fseek(FILE * stream, long int offset, int whence);

The first parameter stream is the pointer to the file. The second parameter is the position of the record to be found, and the third parameter specifies the location where the offset starts.

Od kje v fseek ()
Od kod Pomen
SEEK_SET Začne odmik od začetka datoteke.
SEEK_END Odmik začne s konca datoteke.
SEEK_CUR Začne odmik od trenutne lokacije kurzorja v datoteki.

Primer 5: fseek ()

 #include #include struct threeNum ( int n1, n2, n3; ); int main() ( int n; struct threeNum num; FILE *fptr; if ((fptr = fopen("C:\program.bin","rb")) == NULL)( printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); ) // Moves the cursor to the end of the file fseek(fptr, -sizeof(struct threeNum), SEEK_END); for(n = 1; n < 5; ++n) ( fread(&num, sizeof(struct threeNum), 1, fptr); printf("n1: %d n2: %d n3: %d", num.n1, num.n2, num.n3); fseek(fptr, -2*sizeof(struct threeNum), SEEK_CUR); ) fclose(fptr); return 0; ) 

Ta program bo zapise iz datoteke začel brati program.binv obratnem vrstnem redu (od zadnjega do prvega) in jih natisnil.

Zanimive Članki...