在C语言中,文件调用是非常重要的一个部分,它允许我们读取和写入磁盘上的文件,通过文件调用,我们可以实现数据的持久化存储,以及在不同程序之间传递数据,本文将详细介绍C语言中文件调用的基本概念、操作流程以及一些常用的函数。

c语言中怎么文件调用c语言中怎么文件调用(图片来源网络,侵删)

基本概念

1、文件指针:在C语言中,文件指针是一个指向FILE类型的指针,用于标识一个打开的文件,当我们打开一个文件时,系统会为这个文件分配一个FILE结构体,并将文件指针指向这个结构体。

2、文件类型:C语言中有两种文件类型,分别是文本文件和二进制文件,文本文件是指以字符为单位进行读写的文件,每个字符占一个字节;二进制文件是指以字节为单位进行读写的文件,可以读写任意类型的数据。

3、文件模式:C语言中有三种文件模式,分别是只读模式(’r’)、只写模式(’w’)和读写模式(’a’),只读模式表示只能读取文件内容,不能写入;只写模式表示只能写入文件内容,不能读取;读写模式表示既可以读取文件内容,也可以写入文件内容。

操作流程

C语言中文件调用的基本操作流程如下:

1、打开文件:使用fopen()函数打开一个文件,并返回一个文件指针,如果打开成功,fopen()函数返回非空指针;如果打开失败,fopen()函数返回NULL。

2、读写文件:使用fread()、fwrite()等函数对文件进行读写操作。

3、关闭文件:使用fclose()函数关闭一个已经打开的文件,关闭文件后,不能再对这个文件进行读写操作。

常用函数

1、fopen()函数:用于打开一个文件,其原型为:FILE *fopen(const char *filename, const char *mode);

参数说明:

filename:要打开的文件名,可以是相对路径或绝对路径。

mode:打开文件的模式,如"r"、"w"、"a"等。

返回值:成功打开文件时,返回一个非空的文件指针;失败时,返回NULL。

示例代码:

#include <stdio.h>
int main() {
    FILE *file = fopen("example.txt", "r");
    if (file == NULL) {
        printf("Failed to open file.
");
        return 1;
    }
    // 对文件进行读写操作...
    fclose(file); // 关闭文件
    return 0;
}

2、fclose()函数:用于关闭一个已经打开的文件,其原型为:int fclose(FILE *stream);

参数说明:

stream:要关闭的文件指针。

返回值:成功关闭文件时,返回0;失败时,返回EOF(通常是1)。

示例代码:

#include <stdio.h>
int main() {
    FILE *file = fopen("example.txt", "r");
    if (file == NULL) {
        printf("Failed to open file.
");
        return 1;
    }
    // 对文件进行读写操作...
    if (fclose(file) != 0) {
        printf("Failed to close file.
");
        return 1;
    }
    return 0;
}

3、fread()函数:用于从文件中读取数据,其原型为:size_t fread(void *ptr, size_t size, size_t count, FILE *stream);

参数说明:

ptr:指向要存储数据的缓冲区的指针。

size:每个数据项的大小,以字节为单位。

count:要读取的数据项个数。

stream:要读取数据的文件指针。

返回值:实际读取的数据项个数,如果到达文件末尾或发生错误,返回值可能小于count。

示例代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h> // for read() function in Windows APIs (not needed in Linux/Mac)
#ifdef _WIN32 // Windows specific code block: use the Win32 API function ReadFile() instead of fread() and fwrite() for reading and writing files. This is necessary because fread() and fwrite() are not standard C library functions on Windows. They are part of the C11 standard, but not all C compilers support them yet. The Win32 API function ReadFile() is similar to fread(), but it can also read data from a file that was opened with the "binary" or "text" mode, not just the "text" mode. Here is how you can use it: #define BUFSIZE 4096 int main() { HANDLE hFile; DWORD bytesRead; char buffer[BUFSIZE]; // Open the file in binary mode: hFile = CreateFile("example.bin", //GENERIC_READ, // GENERIC_WRITE, // 0, NULL, //OPEN_EXISTING, //FILE_ATTRIBUTE_NORMAL, NULL); // Read data from the file into the buffer: bytesRead = ReadFile(hFile, buffer, sizeof(buffer), NULL, NULL); if (bytesRead > 0) { // Process the data in the buffer... } else { // Error occurred: display an error message and exit the program. printf("Error %lu: %s when reading from file! GLE=", GetLastError(), strerror(GetLastError())); return 1; } // Close the file handle: CloseHandle(hFile); return 0; } #else // Unixlike systems specific code block: use fread() and fwrite() for reading and writing files. int main() { FILE *file = fopen("example.bin", "rb"); if (file == NULL) { perror("Failed to open file"); return 1; } // Read data from the file into the buffer: size_t bytesRead = fread(buffer, sizeof(char), sizeof(buffer), file); if (bytesRead > 0) { // Process the data in the buffer... } else { // Error occurred: display an error message and exit the program. perror("Error reading from file"); return 1; } // Close the file handle: fclose(file); return 0; } #endif void printBufferContents(const char *buffer) { for (size_t i = 0; i < strlen(buffer); i++) { printf("%c", buffer[i]); } } int main() { char buffer[BUFSIZE]; memset(buffer, 0, sizeof(buffer)); // Read data from the file into the buffer: size_t bytesRead = fread(buffer, sizeof(char), sizeof(buffer), stdin); if (bytesRead > 0) { // Process the data in the buffer... printBufferContents(buffer); } else { // Error occurred: display an error message and exit the program. perror("Error reading from file"); return 1; } return 0; } #endif // End of preprocessor directives (ifdef/ifndef). Note that this code block only works on Unixlike systems (Linux/macOS) and not on Windows. It uses the fread() function to read data from a file into a buffer, and then processes the data in the buffer using a custom printBufferContents() function that prints each character in the buffer on a new line. If an error occurs while reading from the file, it displays an error message and exits with a nonzero status code. If no error occurs, it prints the contents of the buffer and exits successfully with a zero status code.
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。