贝斯特365-365提前结束投注-365bet中国客服电话

C语言 File文件处理 创建和写文件

C语言 File文件处理 创建和写文件

1、创建文件要使用C语言创建文件,可以使用fopen(),此方法返回一个文件指针:文件顺利打开后,指向该流的文件指针就会被返回。若果文件打开失败则返回NULL,并把错误代码存在errno中。

例如,

#include

void CreateFile()

{

//文件指针

FILE *fileP;

char fileName[] = "hello.txt"; //保存在工程目录下

//使用“读入”方式打开文件

fileP = fopen(fileName, "r");

//如果文件不存在

if (fileP == NULL)

{

//使用“写入”方式创建文件

fileP = fopen(fileName, "w");

}

//关闭文件

fclose(fileP);

}

void main()

{

CreateFile();

system("pause");

}

注意:要在特定目录中创建文件(需要权限),需要指定文件的路径,并使用双反斜杠转义“\”字符(对于Windows)。在Mac和Linux上,只需编写路径即可,例如:/Users/cjavapy/filename.txt

2、写文件写文件使用fwrite()方法,将一些文本写入我们在上面的示例中创建的文件中。完成写入文件后,注意应使用fclose()方法将其关闭。

例如,

#include

#define set_s(x,y) {strcpy(s[x].name,y);s[x].size=strlen(y);}

#define nmemb 3

struct test

{

char name[20];

int size;

} s[nmemb];

int main()

{

FILE * stream;

set_s(0,"Linux!");

set_s(1,"FreeBSD!");

set_s(2,"Windows2000.");

stream=fopen("/tmp/fwrite","w");

fwrite(s,sizeof(struct test),nmemb,stream);

fclose(stream);

return 0;

}

1)使用 fprintf() 和 fputs() 写入文

#include

int main() {

// 1. 打开文件(若文件不存在,将自动创建)

FILE *file = fopen("example.txt", "w");

// 检查文件是否成功打开

if (file == NULL) {

printf("Error opening file!\n");

return 1;

}

// 2. 使用 fprintf() 将格式化字符串写入文件

fprintf(file, "This is a line of text.\n");

fprintf(file, "Number: %d, Float: %.2f\n", 42, 3.14);

// 3. 使用 fputs() 写入字符串(不包含格式化)

fputs("This is another line.\n", file);

// 4. 关闭文件

fclose(file);

printf("Data written successfully to example.txt\n");

return 0;

}

2)使用 fwrite() 写入二进制数据

#include

#include

int main() {

// 打开文件用于二进制写入

FILE *file = fopen("data.bin", "wb");

if (file == NULL) {

printf("Error opening file!\n");

return 1;

}

// 要写入的数据

int numbers[] = {1, 2, 3, 4, 5};

size_t count = sizeof(numbers) / sizeof(numbers[0]);

// 使用 fwrite() 将数组写入文件

fwrite(numbers, sizeof(int), count, file);

// 关闭文件

fclose(file);

printf("Binary data written successfully to data.bin\n");

return 0;

}

文件写入还有其它函数,可以参考下面的文档,

相关函数:C语言File文件处理相关函数

3、检查文件是否成功打开

在文件操作中,必须检查 fopen() 是否成功打开文件,否则操作会出错。

#include

int main() {

// 打开文件用于写入(如果文件不存在,则创建它)

FILE *file = fopen("example.txt", "w");

// 检查文件是否成功打开

if (file == NULL) {

perror("Error opening file");

return 1; // 返回错误码

}

// 使用 fprintf 写入文本内容

fprintf(file, "Hello, World!\n");

fprintf(file, "This is a test file.\n");

// 关闭文件以确保内容写入磁盘

fclose(file);

printf("File created and data written successfully.\n");

return 0; // 成功返回 0

}

相关推荐