YouTip LogoYouTip

C File Io

C File I/O

-- Learning is not just about technology, but also about dreams!

C Tutorial

C Language TutorialC IntroductionC Environment SetupC VScodeC Program StructureC Basic SyntaxC Data TypesC VariablesC ConstantsC Storage ClassesC OperatorsC Decision MakingC LoopsC FunctionsC Scope RulesC ArraysC enum (Enumeration)C PointersC Function Pointers and CallbacksC StringsC StructuresC UnionsC Bit FieldsC typedefC Input & OutputC File I/OC PreprocessorsC Header FilesC Type CastingC Error HandlingC RecursionC Variable ArgumentsC Memory ManagementC Undefined BehaviorC Command Line ArgumentsC Safe FunctionsC Sorting AlgorithmsC Project StructureC Language ExamplesC Language Classic 100 ExamplesC Quiz

C Standard Library

C Standard Library - Reference Manual<a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library - ">C Standard Library - <a href="#" title="C Standard Library -

← C Input & Output

C Preprocessors β†’

C File I/O

In the previous chapter, we explained the standard input and output devices handled by the C language. In this chapter, we will introduce how C programmers create, open, and close text or binary files.

A file, whether it is a text file or a binary file, is essentially a sequence of bytes. The C language not only provides functions to access the top level but also provides low-level (OS) calls to handle files on storage devices. This chapter will explain the important calls for file management.

Opening Files

You can use the fopen() function to create a new file or open an existing file. This call initializes an object of type FILE, which contains all the necessary information to control the stream. Below is the prototype of this function call:

FILE *fopen( const char *filename, const char *mode );

Here, filename is a string used to name the file, and the access mode value can be one of the following:

Mode Description
r Opens an existing text file for reading.
w Opens a text file for writing. If the file does not exist, a new file is created. Your program will write content from the beginning of the file. If the file exists, its content is cleared (i.e., the file length is truncated to 0).
a Opens a text file in append mode. If the file does not exist, a new file is created. Your program will append content to the existing file content.
r+ Opens a text file for both reading and writing.
w+ Opens a text file for both reading and writing. If the file exists, it is truncated to zero length. If the file does not exist, a new file is created.
a+ Opens a text file for both reading and writing. If the file does not exist, a new file is created. Reading starts from the beginning, but writing can only be appended.

If handling binary files, use the following access modes instead of the above:

"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"

Closing Files

To close a file, use the fclose() function. The prototype of the function is as follows:

int fclose( FILE *fp );

If the file is closed successfully, the fclose() function returns zero. If an error occurs while closing the file, the function returns EOF. This function, in practice, flushes the data in the buffer, closes the file, and releases all memory used for the file. EOF is a constant defined in the header file stdio.h.

The C standard library provides various functions for reading and writing files character by character or as fixed-length strings.

Writing to a File

Below is the simplest function for writing characters to a stream:

int fputc( int c, FILE *fp );

The fputc() function writes the character value of the parameter c to the output stream pointed to by fp. If the write is successful, it returns the written character; if an error occurs, it returns EOF. You can use the following function to write a null-terminated string to a stream:

int fputs( const char *s, FILE *fp );

The fputs() function writes the string s to the output stream pointed to by fp. If the write is successful, it returns a non-negative value; if an error occurs, it returns EOF. You can also use the int fprintf(FILE *fp,const char *format, ...) function to write a string to a file. Try the following example:

Note: Ensure you have an available tmp directory. If the directory does not exist, you need to create it on your computer first.


/tmp is generally a temporary directory on Linux systems. If you are running on a Windows system, you need to change it to a directory that exists in your local environment, such as: C:tmp, D:tmp, etc.

Example

#include<stdio.h>
int main()
{
    FILE *fp = NULL;
    fp = fopen("/tmp/test.txt", "w+");
    fprintf(fp, "This is testing for fprintf...n");
    fputs("This is testing for fputs...n", fp);
    fclose(fp);
}

When the above code is compiled and executed, it creates a new file test.txt in the /tmp directory and writes two lines using two different functions. Next, let's read this file.

Reading from a File

Below is the simplest function for reading a single character from a file:

int fgetc( FILE * fp );

The fgetc() function reads a character from the input file pointed to by fp. The return value is the read character, or EOF if an error occurs. The following function allows you to read a string from a stream:

char *fgets( char *buf, int n, FILE *fp );

The fgets() function reads n - 1 characters from the input stream pointed to by fp. It copies the read string to the buffer buf and appends a null character at the end to terminate the string.

If this function encounters a newline character 'n' or the end of the file EOF before reading the last character, it returns only the characters read, including the newline character. You can also use the int fscanf(FILE *fp, const char *format, ...) function to read a string from a file, but it stops reading at the first space or newline character.

Example

#include<stdio.h>
int main()
{
    FILE *fp = NULL;
    char buff;
    fp = fopen("/tmp/test.txt", "r");
    fscanf(fp, "%s", buff);
    printf("1: %sn", buff);
    fgets(buff, 255, (FILE*)fp);
    printf("2: %sn", buff);
    fgets(buff, 255, (FILE*)fp);
    printf("3: %sn", buff);
    fclose(fp);
}

When the above code is compiled and executed, it reads the file created in the previous section, producing the following result:

1: This
2: is testing for fprintf...
3: This is testing for fputs...

First, the fscanf() method only reads This because it encounters a space afterward. Next, the call to fgets() reads the remainder until the end of the line. Finally, the call to fgets() reads the second line completely.

Binary I/O Functions

The following two functions are used for binary input and output:

size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);
size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);

These two functions are used for reading and writing blocks of data – usually arrays or structures.

← C Input & Output

C Preprocessors β†’

5 Notes

#0 GGLLCC

122***26@qq.com 159 fseek can move the file pointer to a specified position for reading or insert writing:

int fseek(FILE *stream, long offset, int whence);

fseek sets the current read/write point to offset, where whence can be SEEK_SET, SEEK_CUR, SEEK_END. These values determine whether the offset is calculated from the beginning of the file, the current position, or the end of the file.

You can define a file pointer FILE *fp. When you open a file, the file pointer points to the beginning. To move to a specific number of bytes, you just need to control the offset. For example, relative to the current position...

← Js ConventionsHtml5 Syntax β†’