file_put_contents

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

Writes a string to a file and returns the number of bytes written.

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;
}
Output
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;
}
Output
9

C# v11.0.100

v11.0.100
File.WriteAllText("demo.txt", "hello csharp");
Console.WriteLine(new FileInfo("demo.txt").Length);
Output
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())
}
Output
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));
    }
}
Output
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);
Output
10

PHP v8.6.0

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

Python v3.15.2

v3.15.2
from pathlib import Path

print(Path("demo.txt").write_text("hello python"))
Output
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());
}
Output
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);
Output
8

Language differences

C: fwrite returns the number of items written.

C++: writes via ofstream, then reopens and uses tellg() for the size.

C#: the one-shot File.WriteAllText returns no length, so the example reads back the file size to show the result.

Go: the one-shot os.WriteFile returns no length, so the example reads back the file size to show the result.

Java: the one-shot Files.writeString returns no length, so the example reads back the file size to show the result.

JavaScript: the one-shot Node fs.writeFileSync returns no length, so the example reads back the file size to show the result.

PHP: file_put_contents performs open-write-close in one call and returns the number of bytes written (FILE_APPEND appends).

Python: Path.write_text() directly returns the character count.

Rust: the one-shot fs::write returns no length, so the example reads back the file size to show the result.