U ovom vodiču naučit ćete o rukovanju datotekama na C. Naučit ćete rukovati standardnim I / O u C koristeći fprintf (), fscanf (), fread (), fwrite (), fseek () itd. Uz pomoć primjeri.
Datoteka je spremnik u računalnim uređajima za pohranu koji se koristi za pohranu podataka.
Zašto su potrebne datoteke?
- Kad se program prekine, gube se cjelokupni podaci. Pohranjivanje u datoteci sačuvat će vaše podatke čak i ako se program završi.
- Ako morate unijeti velik broj podataka, trebat će vam puno vremena da ih sve unesete.
Međutim, ako imate datoteku koja sadrži sve podatke, lako možete pristupiti sadržaju datoteke pomoću nekoliko naredbi u C. - Možete bez problema mijenjati podatke s jednog računala na drugo.
Vrste datoteka
Kada imate posla s datotekama, trebate znati dvije vrste datoteka:
- Tekstualne datoteke
- Binarne datoteke
1. Tekstualne datoteke
Tekstualne datoteke su uobičajene .txt datoteke. Tekstne datoteke možete jednostavno stvoriti pomoću bilo kojeg jednostavnog uređivača teksta, kao što je Notepad.
Kada otvorite te datoteke, sav sadržaj unutar datoteke vidjet će se kao običan tekst. Sadržaj možete jednostavno uređivati ili brisati.
Oni se najmanje trude održavati, lako su čitljivi, pružaju najmanje sigurnosti i zauzimaju veći prostor za pohranu.
2. Binarne datoteke
Binarne datoteke su uglavnom .bin datoteke na vašem računalu.
Umjesto da podatke pohranjuju u običnom tekstu, oni ih pohranjuju u binarnom obliku (0 i 1).
Oni mogu sadržavati veću količinu podataka, nisu lako čitljivi i pružaju bolju sigurnost od tekstualnih datoteka.
Datoteke
U C-u možete izvršiti četiri glavne operacije nad datotekama, bilo tekstualne ili binarne:
- Stvaranje nove datoteke
- Otvaranje postojeće datoteke
- Zatvaranje datoteke
- Čitanje i upisivanje podataka u datoteku
Rad s datotekama
Kada radite s datotekama, morate deklarirati pokazivač tipa datoteke. Ova je izjava potrebna za komunikaciju između datoteke i programa.
FILE *fptr;
Otvaranje datoteke - za stvaranje i uređivanje
Otvaranje datoteke izvodi se pomoću fopen()
funkcije definirane u stdio.h
zaglavnoj datoteci.
Sintaksa za otvaranje datoteke u standardnom I / O je:
ptr = fopen("fileopen","mode");
Na primjer,
fopen("E:\cprogram\newprogram.txt","w"); fopen("E:\cprogram\oldprogram.bin","rb");
- Pretpostavimo da datoteka
newprogram.txt
ne postoji na tom mjestuE:cprogram
. Prva funkcija stvara novu datoteku s imenomnewprogram.txt
i otvara je za pisanje prema načinu 'w' .
Način pisanja omogućuje vam stvaranje i uređivanje (prepisivanje) sadržaja datoteke. - Pretpostavimo sada da druga binarna datoteka
oldprogram.bin
postoji na mjestuE:cprogram
. Druga funkcija otvara postojeću datoteku za čitanje u binarnom načinu 'rb' .
Način čitanja omogućuje vam samo čitanje datoteke, a u nju ne možete pisati.
Način rada | Značenje načina | Tijekom nepostojanja spisa |
---|---|---|
r | Otvoreno za čitanje. | Ako datoteka ne postoji, fopen() vraća NULL. |
rb | Otvoreno za čitanje u binarnom načinu. | Ako datoteka ne postoji, fopen() vraća NULL. |
w | Otvoreno za pisanje. | Ako datoteka postoji, njezin se sadržaj prepisuje. Ako datoteka ne postoji, bit će stvorena. |
wb | Otvoreno za pisanje u binarnom načinu. | Ako datoteka postoji, njezin se sadržaj prepisuje. Ako datoteka ne postoji, bit će stvorena. |
a | Otvoreno za dodavanje. Podaci se dodaju na kraj datoteke. | Ako datoteka ne postoji, bit će stvorena. |
ab | Otvoreno za dodavanje u binarnom načinu. Podaci se dodaju na kraj datoteke. | Ako datoteka ne postoji, bit će stvorena. |
r+ | Otvoreno za čitanje i pisanje. | Ako datoteka ne postoji, fopen() vraća NULL. |
rb+ | Otvoren za čitanje i pisanje u binarnom načinu. | Ako datoteka ne postoji, fopen() vraća NULL. |
w+ | Otvoreno za čitanje i pisanje. | Ako datoteka postoji, njezin se sadržaj prepisuje. Ako datoteka ne postoji, bit će stvorena. |
wb+ | Otvoren za čitanje i pisanje u binarnom načinu. | Ako datoteka postoji, njezin se sadržaj prepisuje. Ako datoteka ne postoji, bit će stvorena. |
a+ | Otvoreno za čitanje i dodavanje. | Ako datoteka ne postoji, bit će stvorena. |
ab+ | Otvoren za čitanje i dodavanje u binarnom načinu. | Ako datoteka ne postoji, bit će stvorena. |
Zatvaranje datoteke
Datoteka (i tekstualna i binarna) trebala bi se zatvoriti nakon čitanja / pisanja.
Zatvaranje datoteke izvodi se pomoću 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:
- address of data to be written in the disk
- size of data to be written in the disk
- number of such type of data
- 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.
Različito odakle fseek ()Odakle | Značenje |
---|---|
SEEK_SET | Počinje odmak od početka datoteke. |
SEEK_END | Počinje pomak s kraja datoteke. |
SEEK_CUR | Pokreće pomak od trenutnog mjesta kursora u datoteci. |
Primjer 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; )
Ovaj će program početi čitati zapise iz datoteke program.bin
obrnutim redoslijedom (od zadnjeg do prvog) i ispisati ih.