C-filer I / O: Öppna, läsa, skriva och stänga en fil

I denna handledning lär du dig om filhantering i C. Du lär dig att hantera standard I / O i C med fprintf (), fscanf (), fread (), fwrite (), fseek () etc. med hjälp av exempel.

En fil är en behållare i datalagringsenheter som används för att lagra data.

Varför behövs filer?

  • När ett program avslutas går hela data förlorade. Om du lagrar i en fil kommer dina data att sparas även om programmet avslutas.
  • Om du måste ange ett stort antal data tar det mycket tid att mata in dem alla.
    Men om du har en fil som innehåller all data kan du enkelt komma åt innehållet i filen med några kommandon i C.
  • Du kan enkelt flytta dina data från en dator till en annan utan några ändringar.

Typer av filer

När du hanterar filer finns det två typer av filer du bör känna till:

  1. Textfiler
  2. Binära filer

1. Textfiler

Textfiler är de normala .txt- filerna. Du kan enkelt skapa textfiler med hjälp av alla enkla textredigerare som Anteckningar.

När du öppnar filerna ser du allt innehåll i filen som ren text. Du kan enkelt redigera eller ta bort innehållet.

De tar minimala ansträngningar för att underhålla, är lätta att läsa och ger minst säkerhet och tar större lagringsutrymme.

2. Binära filer

Binära filer är mestadels .bin- filerna på din dator.

Istället för att lagra data i klartext lagrar de det i binär form (0 och 1).

De kan innehålla en högre mängd data, är inte läsbara lätt och ger bättre säkerhet än textfiler.

Filhantering

I C kan du utföra fyra huvudåtgärder på filer, antingen text eller binär:

  1. Skapa en ny fil
  2. Öppna en befintlig fil
  3. Stänga en fil
  4. Läsa från och skriva information till en fil

Arbeta med filer

När du arbetar med filer måste du deklarera en pekare av typfil. Denna deklaration behövs för kommunikation mellan filen och programmet.

 FILE *fptr;

Öppna en fil - för att skapa och redigera

Öppna en fil utförs med den fopen()funktion som definieras i stdio.hrubrikfilen.

Syntaksen för att öppna en fil i standard I / O är:

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

Till exempel,

 fopen("E:\cprogram\newprogram.txt","w"); fopen("E:\cprogram\oldprogram.bin","rb");
  • Låt oss anta att filen newprogram.txtinte finns på platsen E:cprogram. Den första funktionen skapar en ny fil med namnet newprogram.txtoch öppnar den för skrivning enligt läget 'w' .
    I skrivläget kan du skapa och redigera (skriva över) innehållet i filen.
  • Låt oss nu anta att den andra binära filen oldprogram.binfinns på platsen E:cprogram. Den andra funktionen öppnar den befintliga filen för läsning i binärt läge 'rb' .
    Läsläget låter dig bara läsa filen, du kan inte skriva i filen.
Öppningslägen i standard I / O
Läge Betydelse av läge Under obefintlig fil
r Öppet för läsning. Om filen inte finns, fopen()returnerar NULL.
rb Öppen för läsning i binärt läge. Om filen inte finns, fopen()returnerar NULL.
w Öppet för skrivning. Om filen finns skrivs dess innehåll över.
Om filen inte finns kommer den att skapas.
wb Öppet för skrivning i binärt läge. Om filen finns skrivs dess innehåll över.
Om filen inte finns kommer den att skapas.
a Öppna för append.
Data läggs till i slutet av filen.
Om filen inte finns kommer den att skapas.
ab Öppna för att lägga till i binärt läge.
Data läggs till i slutet av filen.
Om filen inte finns kommer den att skapas.
r+ Öppet för både läsning och skrivning. Om filen inte finns, fopen()returnerar NULL.
rb+ Öppet för både läsning och skrivning i binärt läge. Om filen inte finns, fopen()returnerar NULL.
w+ Öppet för både läsning och skrivning. Om filen finns skrivs dess innehåll över.
Om filen inte finns kommer den att skapas.
wb+ Öppet för både läsning och skrivning i binärt läge. Om filen finns skrivs dess innehåll över.
Om filen inte finns kommer den att skapas.
a+ Öppet för både läsning och tillägg. Om filen inte finns kommer den att skapas.
ab+ Öppet för både läsning och tillägg i binärt läge. Om filen inte finns kommer den att skapas.

Stänga en fil

Filen (både text och binär) bör stängas efter läsning / skrivning.

Att stänga en fil utförs med fclose()funktionen.

 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.

Olika varifrån i fseek ()
Varav Menande
SEEK_SET Startar förskjutningen från början av filen.
SEEK_END Startar offset från slutet av filen.
SEEK_CUR Startar förskjutningen från markörens aktuella plats i filen.

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

Detta program kommer att börja läsa posterna från filen program.bini omvänd ordning (sista till första) och skriva ut den.

Intressanta artiklar...