Linux File Programming-fopen function

Source: Internet
Author: User
Tags fread integer numbers modifiers rewind types of functions
1.2 file input and output function keyboard, monitor, printer, disk drive and other logical devices, its input and output can be done through file management methods.
    The most important to use in programming is disk files, so this section is mainly disk files, detailed introduction of the C2.0 provided by turbo-file operation functions, of course, the operation of these files is also suitable for the case of non-disk files. In addition, the Turbo C2.0 provides two types of functions on the file. A class of standard file functions are also called buffer-type file functions, which is a function defined by the ANSI standard; The other class is called non-standard file functions, also called non-buffered file functions. This type of function was first used for UNIX operating systems, but is now available in ms-dos3.0 versions of the operating system.

    The following are described separately. 1.2.1 Standard file function standard file function mainly includes the functions of opening, closing, reading and writing of files. Unlike basic and Fortran, which have sequential files and random files, they should be determined in different ways when they are opened.
    Turbo C2.0 does not distinguish between these two files, but provides two sets of functions, namely sequential read-write functions and random read-write functions. First, the file to open and close any file before and after use, must be opened and closed, because the operating system for the number of open files are limited, DOS operating system, can be in the device. SYS defines the number of files that are allowed to open at the same time (defined with files=n). where n is the number of files that can be opened at the same time, generally n<=20. So you should open the file before you use it to access the information in it. You need to close after use, otherwise there will be some unexpected error.
    The Turbo C2.0 provides functions for opening and closing files. 1. The fopen () function fopen function is used to open a file, which is called in the following format:FILE*fopen (Char *filename, *type);
    Before introducing this function, let's take a look at the following knowledge. (1) Streams and file (file) streams and files are different in Turbo C2.0, and Turbo C2.0 provides a layer of abstraction between the programmer and the accessed device, called "Flow", and the actual device is referred to as a file. A stream is a logical device that has the same behavior. Therefore, the function used to write the disk file can also be used to write the printer. There are two types of streams in the Turbo C2.0: text stream and binary (binary stream). is a text file and binary file for disk.
    The software makes it easy for readers to understand the Turbo C2.0 language without special distinction between convection and file. (2) Files pointer file is actually a new data type. It is a collection of the basic data types of the turbo C2.0, called the structure pointer.
    The concept of structs will be described in detail in section fourth, where file is understood as a data structure that includes information about file management, that is, you must first define a file pointer when you open it. (3) The function call format described later will directly write out the data type of the formal parameter and the data type of the function return value. For example, the function that opens the file above returns a file pointer with two formal arguments, both character variables (string arrays or string pointers).
    The software no longer describes the calling format of the function in detail.
    Now let's look at the use of open file functions. The first form parameter in the fopen () function represents the file name and can contain both the path and the file name. such as: "B:test." DAT "" C://tc//test. DAT "If the path is written as" c:/tc/test.
    DAT "is not correct, this point should pay special attention to. The second form parameter represents the type of open file.
                       The requirements for file types are shown in the following table.           Table file action type ━━━━━━━━━━━━━━━━━━━━━━━━━━━━ character meaning ──────────────────────────── "R"         Open Text file Read Only "W" Create text File Write "a" only  Add, if the file does not exist then create a "r+" open a text file read/write "w+" Create a text file read/write "A +" open or create
    Create a file supplement "B" binary file (can be combined with each of the above) "T" text this file (default) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    If you want to open a Ccdos subdirectory, the file name is a clib binary file that can be written as: fopen ("C://ccdos//clib", "RB"); If a file is successfully opened, the fopen () function returns the file pointer, otherwise null (NULL).
    This allows you to determine whether the file was opened successfully.
       2. The fclose () function fclose () function to close a file opened by the fopen () function, which is called in the following format:intFcloseFILE*stream); The function returns an integer number. Returns 0 when a file is closed successfully, otherwise a value other than 0 is returned.
    You can determine whether a file is closed successfully based on the return value of the function. Example: #iclude <stdio.h> main () {FILE*FP; /* Define a file pointer/*intI  Fp=fopen ("Clib", "RB"); /* Open the file with the current directory named Clib Read Only */if(fp==null)/* Determine whether the file is open successfully/puts ("File open Error"),/* Prompt Open unsuccessful * * I=fclose (FP); /* Close Open File * *if(i==0)/* To determine whether the file is closed successfully/printf ("o,k"); /* Prompt Shutdown Success */ElsePuts ("File close error");//prompt shutdown unsuccessful/} II, functions related to file operation the file read-write function in this section refers to sequential reading and writing, that is, after reading and writing a message, the pointer automatically adds 1.

    The following is a description of the write operation function and the read operation function respectively. 1. The sequential write function of the file fprintf (), fputs (), and FPUTC () function Functions fprintf (), fputs (), and FPUTC () are the sequential write functions of the file, and the calling format is as follows:intfprintf (FILE*stream,Char*format, <variable-list>);intFputsChar*string,FILE*steam);intFPUTC (intChFILE*steam); The return values of the above three functions are integral types. The return value of the fprintf () function is the number of characters (in bytes) that are actually written to the file. If write error, return a negative number, the fputs () function returns 0 o'clock indicates that the operation of the string pointer to the file was successful, and returned not 0 o'clock to indicate that the write operation failed.
     The FPUTC () function returns a value that writes to the file, at which point the write operation succeeds, otherwise the EOF (defined in stdio.h) for the completion of the end of the file indicates a write error. The formatting in the fprintf () function is the same as the printf () function, except that the fprintf () function is written to the file.
    and printf () is output to the screen.
    Below is an example of running a Test.dat file after childbirth. Example: #include <stdio.h> main () {Char*s= "That ' s good news"); /* Define string pointer and initialize/*inti=617; /* Define integer variable and initialize/*FILE*FP;    /* Definition file pointer/* FP=FOPNE ("Test.dat", "w");               /* Create a text file to write only/fputs ("Your score of Toeflis", FP);/* Write a string of characters to the created file/FPUTC (': ', FP);       /* Write a colon to the file: * * fprintf (FP, "%d/n", I);         * * Write an integer to the file/fprintf (FP, "%s", s);                   /* Write a string to the file/fclose (FP); /* Close File/} The DOS Type command displays the contents of the TEST.DAT as follows: screen displays Your score of TOEFL is:617 that ' s good news 2 . The sequential read operation functions of the Files fscanf (), fgets (), and fgetc () function Functions fscanf (), fgets (), and fgetc () are sequential read operations functions of the file, and their invocation format is as follows:intfscanfFILE*stream,Char*format, <address-list>);CharFgetsChar*string,intNFILE*steam);intFGETC (FILE*steam); The use of the FSCANF () function is similar to the scanf () function, except that it reads information from a file. The return value of the fscanf () function is EOF (that is,-1), indicating a read error, otherwise the read data is successful. The fgets () function reads up to n-1 characters from a file (n is used to specify the number of characters) and puts them in the string pointed to by a string, automatically adding a null character to the end of the string after it is read, and reading succeeds returning a string pointer, which fails to return a null pointer.
    The FGETC () function returns a character at the current position of the file, which returns EOF when reading an error.
    The following program reads the Test.dat file produced by example 11 and displays the results of the readout on the screen. Example #include <stdio.h> main () {Char*s, m[20];intIFILE*FP;    Fp=fopen ("Test.dat", "R");             /* Open Text file read Only/fgets (S, FP);              /* Reads 23 characters from the File/printf ("%s", s);         /* Output Read String * * FSCANF (FP, "%d", &i);              /* Read integer number/printf ("%d", I);           * * Output read integer/Putchar (fgetc (FP));             /* Read a character at the same time output */fgets (M,, FP);                      /* Read 16 characters/* puts (m);                   * * Output Read string/fclose (FP);                      * * Close File/getch (); /* Wait for any key/} run after the screen display: Your score of TOEFL is:617 that ' s good news if the previous example fscanf (FP, "%d", &i) to FSC ANF (FP, "%s", m), and then change the subsequent output statement to printf ("%s", m), the same result can be obtained. This shows Turbo C2. If you are reading a text file in 0, both the character and the number will be processed according to its ASCII value.

    The other thing to note is that the fscanf () function will automatically end when it reads a blank character, especially when used. 3. Random Read and write files sometimes the user wants to read the information directly in the middle of the file, and it is obviously inconvenient to read and write the file in the order that it must start from the file head until the requested file location.
    The Turbo C2.0 provides a random read-write function of a set of files, that is, the position pointer can be positioned directly to read and write in the place where the file is requested. The random Read and write functions of the file are as follows:intFseek (FILE*stream,LongOffsetintFromwhere);intFreadvoid*buf,intSizeintCountFILE*stream);intFwrite (void*buf,intSizeintCountFILE*stream);LongFtell (FILE*stream); The role of the fseek () function is to set the position pointer of the file to the position of offset bytes starting at Fromwhere, where Fromwhere is one of several macro definitions: file position pointer start calculation position Fromwhere ━━━━━━━━━━━━━━━━━━━━━━━━━━━ symbol constant numeric meaning ───────────────────────────seek_set 0 from file The opening seek_cur 1 from the current position of the file pointer Seek_end 2 from the end of the file ━━━━━━━━━━━━━━━━━━━━━━━━━━━offset means The number of bytes skipped by the file position pointer from the specified start position (where Fromwhere indicates). It is a long integer to support files larger than 64K bytes.
    The fseek () function is typically used to manipulate binary files.
    When the fseek () function returns 0 o'clock to indicate that the operation was successful, a return of 0 does not represent a failure.
    The following program reads the 8th byte from the binary file Test_b.dat. Example: #include <stdio.h> main () {FILE*FP;if((Fp=fopen ("Test_b.dat", "RB")) ==null)
              {printf ("Can ' t Open file");
            Exit (1);
          Fseek (FP, 8.1, Seek_set);
          FGETC (FP);
     Fclose (FP);
    The Fread () function reads count fields from a file, each with a size byte and stores them in the buffer that the BUF pointer refers to.
    The fwrite () function writes the count field of size bytes in the buffer that the BUF pointer refers to to the file to which the stream points. As the number of read and write sections increases, so does the file position indicator, the number of bytes read, and the number of bytes that the file position indicator skips accordingly.
    Read-write function returns the number of fields that are read and written.
    The Ftell () function returns the current value of the file position indicator, which is the number of bytes that the indicator starts at the beginning of the file, and the number returned is a long integer, indicating an error when returning-1.
    The following program writes a floating-point number group to the file Test_b.dat in binary form. Example: #include <stdio.h> main () {floatf[6]={3.2,-4.34, 25.04, 0.1, 50.56, 80.5}; /* Define floating-point number groups and initialize/*intIFILE*FP; Fp=fopen ("Test_b.dat", "WB"); /* Create a binary file only write */fwrite (F,sizeof(float, 6, FP);//* 6 floating-point numbers are written to the file/* fclose (FP);
    /* Close File/} The following example reads 100 integer numbers from the Test_b.dat file and places them in the DAT array. Example: #include <stdio.h> main () {FILE*FP;intDAT[100]; Fp=fopen ("Test_b.dat", "RB");/* Open a binary file read only */if(Fread (DAT,sizeof(int)/*!=100)/* To determine whether or not to read 100 numbers * *if(feof (FP)) printf ("End of File"); /* Less than 100 files end of document * *Elseprintf ("Read error");                   /* Reading Error */fclose (FP); /* Close File/} Note: When using standard file functions to read and write files to the file, first put the content read and write into the buffer, that is, write function only to output buffer operation, read function only to the input buffer operation. For example, the contents of the buffer are written to a file and the content is first placed in the output buffer until the output buffer is full or the fclose () function is used to close the file. Without the fclose () function, the written content is not saved to the file or the contents of the file written are not complete. There is a function that refreshes the buffer, that is, fflush (), which is called in the form of:intFflush (FILE*stream);

    This function actually writes the contents of the output buffer to the file and clears the contents of the input buffer. 4. The feof () and rewind () functions are called in the following format:intFeofFILE*stream);intRewind (FILE*stream); The feof () function detects whether the file location indicator has reached the end of the file, or returns a value other than 0, or 0. This function is particularly useful for binary file operations, because the end of file flag EOF is also a legitimate binary number, simply checking the value of the read characters to determine whether the file is finished or not.
    If that is the case, it may cause the file to not end and is considered the end, so you must have the feof () function. The following statement is a common way to determine whether a file is closed or not. while(!feof (FP)) fgetc (FP);
    While is the circular statement, which is described below.


    The rewind () function is used to move the file position indicator to the beginning of the file, returning 0 if it succeeds, otherwise, the value is not 0. Functions such as 1.2.2 Non-standard file functions were first used for UNIX operating systems, the ANSI standard is undefined, but sometimes it is often used, and DOS 3.0 versions support these functions.
    Their header file is io.h. Opening and closing of documents 1. The open () function opens () function by opening the file, which is called in the following format:intOpenChar*filename,intAccess); This function indicates that the file named filename is opened as required by access, and the return value is a file descriptor, where access has two parts: basic mode and modifiers, both of which are connected in the form of "(or"). Modifiers can have multiple, but only one of the basic patterns.
               Access rules are shown in table 3-2.   Table 3-2 Access rules ━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Basic mode meaning modifier meaning ────────────────────────────o_rdonly read-only The O_append file pointer points to the end o_wronly write-only o_creat files do not exist, and properties are o_rdwr read-write by basic pattern Properties O_tru NC if file exists, its length is reduced to 0, the property is unchanged o_binary open a binary file O_tex

    T Open a text file the ━━━━━━━━━━━━━━━━━━━━━━━━━━━━open () function opens successfully, and the return value is the value of the file descriptor (non-negative), otherwise return 1. 2. The close () function closes the file opened by the open () function, which is called in the following format:intCloseinthandle);

    This function closes the file description Word handle the attached file. Second, read and write function 1. The read () function's invocation format is:intReadintHandlevoid*buf,intcount); The read () function reads the count bytes into the buffer referred to in BUF from the handle (file descriptor) file, the return value is the actual number of bytes read, and return 1 indicates an error.

    A return of 0 indicates the end of the file. 2. The call format for the write () function is:intWriteintHandlevoid*buf,intcount);

    The write () function writes count bytes from the buffer pointed to by the BUF to the handle-connected file, and the return value is the number of bytes actually written. Third, the random positioning function 1. The call format for the Lseek () function Lseek () function is:intLseek (intHandleLongOffsetintFromwhere);

    This function locates the file position pointer attached to the handle, with the same functionality and usage as the fseek () function. 2. The call format of the tell () function tell () function is:LongTellint handle); This function returns the current location pointer of the file attached to the handle, with the same functionality and usage as Ftell ().
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.