file_put_contents

file_put_contents(string $filename, mixed $data, int $flags = 0): int|false

把字符串写入文件,返回写入的字节数。

C C23

C23
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *text = "hello c";
    FILE *fp = fopen("demo.txt", "w");
    size_t n = fwrite(text, 1, strlen(text), fp);
    fclose(fp);
    printf("%zu\n", n);
    return 0;
}
输出
7

C++ C++26

C++26
#include <fstream>
#include <iostream>
int main() {
    {
        std::ofstream out("demo.txt");
        out << "hello cpp";
    }
    std::ifstream in("demo.txt", std::ios::binary | std::ios::ate);
    std::cout << in.tellg() << "\n";
    return 0;
}
输出
9

C# v11.0.100

v11.0.100
File.WriteAllText("demo.txt", "hello csharp");
Console.WriteLine(new FileInfo("demo.txt").Length);
输出
12

Go v1.27.4

v1.27.4
package main

import (
    "fmt"
    "os"
)

func main() {
    os.WriteFile("demo.txt", []byte("hello go"), 0644)
    info, _ := os.Stat("demo.txt")
    fmt.Println(info.Size())
}
输出
8

Java v27.0.1

v27.0.1
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
    public static void main(String[] args) throws Exception {
        Path path = Path.of("demo.txt");
        Files.writeString(path, "hello java");
        System.out.println(Files.size(path));
    }
}
输出
10

JavaScript v26.13.1

v26.13.1
const fs = require("node:fs");
fs.writeFileSync("demo.txt", "hello node");
console.log(fs.statSync("demo.txt").size);
输出
10

PHP v8.6.0

v8.6.0
echo file_put_contents("demo.txt", "hello php");
输出
9

Python v3.15.2

v3.15.2
from pathlib import Path

print(Path("demo.txt").write_text("hello python"))
输出
12

Rust v1.99.1

v1.99.1
use std::fs;

fn main() {
    fs::write("demo.txt", "hello rust").unwrap();
    println!("{}", fs::metadata("demo.txt").unwrap().len());
}
输出
10

TypeScript v26.13.1

v26.13.1
import * as fs from "node:fs";
fs.writeFileSync("demo.txt", "hello ts");
console.log(fs.statSync("demo.txt").size);
输出
8

语言差异说明

C:fwrite 返回写入元素个数。

C++:ofstream 写入后重新打开并 tellg() 取文件大小。

C#:一次性写入 File.WriteAllText 不返回长度,示例通过读回文件大小展示结果。

Go:一次性写入 os.WriteFile 不返回长度,示例通过读回文件大小展示结果。

Java:一次性写入 Files.writeString 不返回长度,示例通过读回文件大小展示结果。

JavaScript:一次性写入 Node fs.writeFileSync 不返回长度,示例通过读回文件大小展示结果。

PHP:file_put_contents 是「打开-写入-关闭」一步到位的写入,返回写入字节数(FILE_APPEND 标志可追加)。

Python:Path.write_text() 直接返回写入字符数。

Rust:一次性写入 fs::write 不返回长度,示例通过读回文件大小展示结果。