码迷,mamicode.com
首页 > 其他好文 > 详细

File I/O

时间:2020-05-19 12:24:55      阅读:53      评论:0      收藏:0      [点我收藏+]

标签:char   over   any   items   null   utc   sim   main   iss   

To read a file in C, you must create a pointer to the file.  To do this, you use the FILE data type:

#include <stdio.h>   /* You need this include file to access the FILE type */

FILE  *myFile;


At this point, myFile is not initialized.  You initialize it using the fopen() function:

Opening a File
The prototype for fopen is:
FILE *fopen(const char *filename, const char *mode);

Notice that fopen() has two arguments, the filename and the mode that you will use to open the file.
Both the filename and mode arguments are strings:
myFile = fopen("MyDataFile.txt", "r");   /* An example statement to open a file in read mode */

The characters used for the mode are:

  • r  - open for reading
  • w  - open for writing (file need not exist)
  • a  - open for appending (file need not exist)
  • r+ - open for reading and writing, start at beginning
  • w+ - open for reading and writing (overwrite file)
  • a+ - open for reading and writing (append if file exists)

For your first programs, you will generally only use the "r" and "w" modes.  Note that if you open a file for writing or appending (adding data to the end of a file), the file does not need to exist.  However, if you open a file for reading, the file must exist before opening it.  If the file cannot be found, then the fopen() function returns a NULL pointer.  Therefore, it is good programming practice to always check the result of a call to fopen(), even if the mode is "w" or "a":

myFile = fopen("MyDataFile.txt", "r");
if (myFile == NULL)
{
      /* Print an error message */
       exit(0);
}


If the file to be opened is not in the same directory as the program, then the full or relative path to the file must be used when opening the file.  Otherwise, the  program will not be able to find the file, and the fopen() will return a NULL pointer.
myFile = fopen("/home/mydir/MyDataFile.txt", "r");

Closing a File
For every instance where a program opens a file, there must be a corresponding fclose().  If you fail to close a file before exiting a program, there may be data that has not been flushed from the buffer into the file, especially a file which was opened for writing.  The prototype for fclose() is:
int fclose(FILE *a_file);

So, to close the file we opened in our example above, we would write:
fclose(myFile);
Note that we use the file pointer as the argument - NOT the filename we used to open the file.

Reading from an ASCII File
Reading from file containing ASCII data is similar to reading user input using scanf().  The main difference is that the fscanf() function is used:
int fscanf(FILE *stream, const char *format, ... );

The fscanf() function has the pointer to the file as its first parameter:
fscanf(myFile, "%d", &myNum);   /* Read a number from the file pointed to by myFile */

You can also read single characters from the file using fgetc():
char someChar = fgetc(myFile);


Writing to an ASCII File
Writing ASCII data to a file is similar to printing using the printf() function.  The main difference is that the fprintf function is used:
int fprintf(FILE *stream, const char *format, ...);

The fprintf() function has the pointer to the file as its first parameter:
fprintf(myFile, "%s", someName);  /* Write the string referenced by someName to the file pointed to by myFile */

You can also write single characters to the file using fputc():
fputc(someChar, myFile);  /* Note that the pointer to the file is the second parameter in fputc() */

Binary I/O
Sometimes, a program will read and write binary data from and to a file.  For instance, suppose the following struct is declared:
typedef struct myStruct
{
    int someInt;
    char someChar;
    char someString[25];
};


To write an instance of this structure to a file, we must first open the file in binary mode.  To do this, we use the fopen() function but add a "b" to the mode parameter:
myFile = fopen("MyDataFile.dat", "wb");   /* An example statement to open a binary file in write mode */

Once the binary file is opened, data is written to the file using the fwrite() function.  This function writes data to the file in memory blocks.  In other words, you must state how many items you intend to write, as well as the size of each item:

myStruct  someItem;
/* Assume someItem is initialized */
int itemsWritten = fwrite(&someItem, sizeof(myStruct), 1, myFile);   /* Write the data contained in someItem to the file pointed to by myFile */

If the write was successful, itemsWritten will be equal to 1. If multiple items are written, then itemsWritten will be equal to the number of items that were successfully written. If this value does not equal the third parameter in the fwrite() function, then further calls to fwrite() must be made to write all the data. Usually this is not an issue for file I/O, but can be an issue if reading or writing to/from a serial port or other device.

Reading data from a binary file is done using the fread() function.  This function is similar to the fwrite() function in that you need to state how many items you are reading, and the size of an individual item:
int itemsRead = fread(&someItem, sizeof(myStruct), 1, myFile);
If the read was successful, itemsRead will be equal to 1. The itemsRead value for fread() mirrors the itemsWritten value in the call to fwrite().

File I/O

标签:char   over   any   items   null   utc   sim   main   iss   

原文地址:https://www.cnblogs.com/JasperZhao/p/12916079.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!