file_get_contents
file_get_contents(string $filename): string|false
把整个文件读入一个字符串。
C C23
C23
#include <stdio.h>
#include <string.h>
int main(void) {
const char *text = "hello c";
FILE *out = fopen("demo.txt", "w");
fwrite(text, 1, strlen(text), out);
fclose(out);
FILE *in = fopen("demo.txt", "r");
char buf[64];
size_t n = fread(buf, 1, sizeof buf - 1, in);
buf[n] = '\0';
fclose(in);
printf("%s\n", buf);
return 0;
}
输出
hello c
C++ C++26
C++26
#include <fstream>
#include <iostream>
#include <iterator>
int main() {
{
std::ofstream out("demo.txt");
out << "hello cpp";
}
std::ifstream in("demo.txt");
std::string content((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
std::cout << content << "\n";
return 0;
}
输出
hello cpp
C# v11.0.100
v11.0.100
File.WriteAllText("demo.txt", "hello csharp");
Console.Write(File.ReadAllText("demo.txt"));
输出
hello csharp
Go v1.27.4
v1.27.4
package main
import (
"fmt"
"os"
)
func main() {
os.WriteFile("demo.txt", []byte("hello go"), 0644)
data, _ := os.ReadFile("demo.txt")
fmt.Print(string(data))
}
输出
hello go
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.print(Files.readString(path));
}
}
输出
hello java
JavaScript v26.13.1
v26.13.1
const fs = require("node:fs");
fs.writeFileSync("demo.txt", "hello node");
console.log(fs.readFileSync("demo.txt", "utf8"));
输出
hello node
PHP v8.6.0
v8.6.0
file_put_contents("demo.txt", "hello php");
echo file_get_contents("demo.txt");
输出
hello php
Python v3.15.2
v3.15.2
from pathlib import Path
Path("demo.txt").write_text("hello python")
print(Path("demo.txt").read_text())
输出
hello python
Rust v1.99.1
v1.99.1
use std::fs;
fn main() {
fs::write("demo.txt", "hello rust").unwrap();
print!("{}", fs::read_to_string("demo.txt").unwrap());
}
输出
hello rust
TypeScript v26.13.1
v26.13.1
import * as fs from "node:fs";
fs.writeFileSync("demo.txt", "hello ts");
console.log(fs.readFileSync("demo.txt", "utf8"));
输出
hello ts
语言差异说明
C:无一次性读取函数,用 fopen+fread 读进缓冲(本例为演示先写出文件)。
C++:无一次性读取函数,用 std::ifstream 配 istreambuf_iterator 读出全部字符。
C#:File.ReadAllText 是同等的一次性文本读取。
Go:用 os.ReadFile 返回字节切片。
Java:Java 11+ 的 Files.readString 是同等的一次性文本读取。
JavaScript:Node 用 fs.readFileSync 并显式传编码。
PHP:file_get_contents 一次性读整文件为字符串,失败返回 false。
Python:Path.read_text() 是同等的一次性文本读取。
Rust:fs::read_to_string 是同等的一次性文本读取。