C Files I / O: openen, lezen, schrijven en sluiten van een bestand

In deze tutorial leer je over het omgaan met bestanden in C. Je leert omgaan met standaard I / O in C met behulp van fprintf (), fscanf (), fread (), fwrite (), fseek () etc. met behulp van voorbeelden.

Een bestand is een container op computeropslagapparaten die worden gebruikt voor het opslaan van gegevens.

Waarom zijn bestanden nodig?

  • Wanneer een programma wordt beëindigd, gaan alle gegevens verloren. Als u in een bestand opslaat, blijven uw gegevens behouden, zelfs als het programma wordt beëindigd.
  • Als u een groot aantal gegevens moet invoeren, kost het veel tijd om ze allemaal in te voeren.
    Als u echter een bestand heeft met alle gegevens, kunt u eenvoudig toegang krijgen tot de inhoud van het bestand met een paar opdrachten in C.
  • U kunt uw gegevens gemakkelijk en zonder wijzigingen van de ene computer naar de andere verplaatsen.

Soorten bestanden

Als u met bestanden omgaat, zijn er twee soorten bestanden die u moet kennen:

  1. Tekstbestanden
  2. Binaire bestanden

1. Tekstbestanden

Tekstbestanden zijn de normale .txt- bestanden. U kunt eenvoudig tekstbestanden maken met behulp van eenvoudige teksteditors zoals Kladblok.

Wanneer u die bestanden opent, ziet u alle inhoud in het bestand als platte tekst. U kunt de inhoud gemakkelijk bewerken of verwijderen.

Ze kosten weinig onderhoud, zijn gemakkelijk leesbaar en bieden de minste beveiliging en nemen meer opslagruimte in beslag.

2. Binaire bestanden

Binaire bestanden zijn meestal de .bin- bestanden op uw computer.

In plaats van gegevens op te slaan in platte tekst, slaan ze deze op in de binaire vorm (nullen en enen).

Ze kunnen een grotere hoeveelheid gegevens bevatten, zijn niet gemakkelijk leesbaar en bieden een betere beveiliging dan tekstbestanden.

Bestandsbewerkingen

In C kunt u vier belangrijke bewerkingen uitvoeren op bestanden, tekst of binair:

  1. Een nieuw bestand aanmaken
  2. Een bestaand bestand openen
  3. Een bestand sluiten
  4. Lezen uit en schrijven van informatie naar een bestand

Werken met bestanden

Wanneer u met bestanden werkt, moet u een aanwijzer van het type bestand aangeven. Deze verklaring is nodig voor de communicatie tussen het bestand en het programma.

 FILE *fptr;

Een bestand openen - om te maken en te bewerken

Het openen van een bestand wordt uitgevoerd met behulp van de fopen()functie die is gedefinieerd in het stdio.hheaderbestand.

De syntaxis voor het openen van een bestand in standaard I / O is:

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

Bijvoorbeeld,

 fopen("E:\cprogram\newprogram.txt","w"); fopen("E:\cprogram\oldprogram.bin","rb");
  • Laten we aannemen dat het bestand newprogram.txtniet op de locatie bestaat E:cprogram. De eerste functie maakt een nieuw bestand aan met de naam newprogram.txten opent het om te schrijven volgens de modus 'w' .
    Met de schrijfmodus kunt u de inhoud van het bestand maken en bewerken (overschrijven).
  • Laten we nu aannemen dat het tweede binaire bestand oldprogram.binop de locatie bestaat E:cprogram. De tweede functie opent het bestaande bestand voor lezen in binaire modus 'rb' .
    In de leesmodus kunt u alleen het bestand lezen, u kunt niet naar het bestand schrijven.
Openingsmodi in standaard I / O
Modus Betekenis van modus Tijdens het bestaan ​​van een bestand
r Open om te lezen. Als het bestand niet bestaat, fopen()wordt NULL geretourneerd.
rb Open voor lezen in binaire modus. Als het bestand niet bestaat, fopen()wordt NULL geretourneerd.
w Open voor schrijven. Als het bestand bestaat, wordt de inhoud overschreven.
Als het bestand niet bestaat, wordt het aangemaakt.
wb Open voor schrijven in binaire modus. Als het bestand bestaat, wordt de inhoud overschreven.
Als het bestand niet bestaat, wordt het aangemaakt.
a Open voor toevoegen.
De gegevens worden aan het einde van het bestand toegevoegd.
Als het bestand niet bestaat, wordt het aangemaakt.
ab Open voor toevoegen in binaire modus.
De gegevens worden aan het einde van het bestand toegevoegd.
Als het bestand niet bestaat, wordt het aangemaakt.
r+ Open voor zowel lezen als schrijven. Als het bestand niet bestaat, fopen()wordt NULL geretourneerd.
rb+ Open voor zowel lezen als schrijven in binaire modus. Als het bestand niet bestaat, fopen()wordt NULL geretourneerd.
w+ Open voor zowel lezen als schrijven. Als het bestand bestaat, wordt de inhoud overschreven.
Als het bestand niet bestaat, wordt het aangemaakt.
wb+ Open voor zowel lezen als schrijven in binaire modus. Als het bestand bestaat, wordt de inhoud overschreven.
Als het bestand niet bestaat, wordt het aangemaakt.
a+ Open voor zowel lezen als toevoegen. Als het bestand niet bestaat, wordt het aangemaakt.
ab+ Open voor zowel lezen als toevoegen in binaire modus. Als het bestand niet bestaat, wordt het aangemaakt.

Een bestand sluiten

Het bestand (zowel tekst als binair) moet worden gesloten na lezen / schrijven.

Het sluiten van een bestand wordt uitgevoerd met de fclose()functie.

 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.

Anders waar in fseek ()
Vanwaar Betekenis
SEEK_SET Start de offset vanaf het begin van het bestand.
SEEK_END Begint de offset vanaf het einde van het bestand.
SEEK_CUR Start de offset vanaf de huidige locatie van de cursor in het bestand.

Voorbeeld 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; ) 

Dit programma begint de records uit het bestand program.binin omgekeerde volgorde (van de laatste naar de eerste) te lezen en drukt deze af.

Interessante artikelen...