fscanf
fscanf(resource $stream, string $format, mixed &...$vars): array|int|false
Parses fields from a file stream by a format string: the file-stream sibling of sscanf (sscanf covered in A24); without by-reference variables it returns the parsed array, and false at EOF; the return-value semantics (assigned-field count) align with the C fscanf family.
C C23
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void) {
char path[] = "/tmp/fsc_c_XXXXXX";
int fd = mkstemp(path);
FILE *f = fdopen(fd, "w+");
fputs("Alice 25\nBob 30\n", f);
rewind(f);
char name[32];
int age;
// fscanf is scanf(3) reading from a stream: returns the converted-field count
int n = fscanf(f, "%31s %d", name, &age);
printf("%d %s %d\n", n, name, age); // 2 Alice 25
n = fscanf(f, "%31s %d", name, &age);
printf("%d %s %d\n", n, name, age); // 2 Bob 30
n = fscanf(f, "%31s %d", name, &age); // EOF: no conversion
printf("%d\n", n); // -1 (EOF)
fclose(f);
unlink(path);
return 0;
}
2 Alice 25 2 Bob 30 -1
C++ C++26
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
int main() {
char path[] = "/tmp/fsc_cpp_XXXXXX";
int fd = mkstemp(path);
FILE *f = fdopen(fd, "w+");
std::fputs("Alice 25\nBob 30\n", f);
std::rewind(f);
char name[32];
int age;
// fscanf is scanf(3) reading from a stream: returns the converted-field count
int n = std::fscanf(f, "%31s %d", name, &age);
std::printf("%d %s %d\n", n, name, age); // 2 Alice 25
n = std::fscanf(f, "%31s %d", name, &age);
std::printf("%d %s %d\n", n, name, age); // 2 Bob 30
n = std::fscanf(f, "%31s %d", name, &age); // EOF: no conversion
std::printf("%d\n", n); // -1 (EOF)
std::fclose(f);
unlink(path);
return 0;
}
2 Alice 25 2 Bob 30 -1
C# v11.0.100
using System.IO;
var path = Path.GetTempFileName();
File.WriteAllText(path, "Alice 25\nBob 30\n");
// C# has no scanf family: split each line and parse typed fields
foreach (var line in File.ReadLines(path))
{
var parts = line.Split(' ');
string name = parts[0];
int age = int.Parse(parts[1]);
Console.WriteLine($"{name} {age}");
}
File.Delete(path);
Alice 25 Bob 30
Go v1.27.4
package main
import (
"fmt"
"os"
)
func main() {
path := fmt.Sprintf("%s/fsc_go_%d", os.TempDir(), os.Getpid())
os.WriteFile(path, []byte("Alice 25\nBob 30\n"), 0644)
f, _ := os.Open(path)
defer f.Close()
// fmt.Fscanf is scanf(3) reading from an io.Reader: returns field count + error
var name string
var age int
n, _ := fmt.Fscanf(f, "%s %d", &name, &age)
fmt.Println(n, name, age) // 2 Alice 25
n, _ = fmt.Fscanf(f, "%s %d", &name, &age)
fmt.Println(n, name, age) // 2 Bob 30
n, err := fmt.Fscanf(f, "%s %d", &name, &age)
fmt.Println(n, err != nil) // 0 true: EOF
}
2 Alice 25 2 Bob 30 0 true
Java v27.0.1
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
Path p = Files.createTempFile("fsc", ".txt");
Files.write(p, "Alice 25\nBob 30\n".getBytes());
// no scanf format strings: Scanner reads typed tokens from a stream
Scanner sc = new Scanner(p);
String name = sc.next();
int age = sc.nextInt();
System.out.println(name + " " + age); // Alice 25
name = sc.next();
age = sc.nextInt();
System.out.println(name + " " + age); // Bob 30
System.out.println(sc.hasNext()); // false: EOF
sc.close();
}
}
Alice 25 Bob 30 false
JavaScript v26.13.1
const fs = require("fs");
const os = require("os");
const path = require("path");
const file = path.join(fs.mkdtempSync(os.tmpdir() + "/fsc_"), "data.txt");
fs.writeFileSync(file, "Alice 25\nBob 30\n");
// JavaScript has no scanf: read the file and split each line
const lines = fs.readFileSync(file, "utf8").trim().split("\n");
for (const line of lines) {
const [name, age] = line.split(" ");
console.log(name, age);
}
fs.unlinkSync(file);
Alice 25 Bob 30
PHP v8.6.0
$path = tempnam(sys_get_temp_dir(), 'fsc_');
file_put_contents($path, "Alice 25\nBob 30\n");
$f = fopen($path, 'r');
// fscanf: the file-stream sibling of sscanf — returns the parsed array
$row = fscanf($f, "%s %d");
echo $row[0], ' ', $row[1], "\n"; // Alice 25
list($name, $age) = fscanf($f, "%s %d");
echo $name, ' ', $age, "\n"; // Bob 30
fclose($f);
unlink($path);
Alice 25 Bob 30
Python v3.15.2
import os
import tempfile
fd, path = tempfile.mkstemp(prefix="fsc_")
os.close(fd)
with open(path, "w") as f:
f.write("Alice 25\nBob 30\n")
# Python has no scanf: read line by line and split + int() (the idiomatic equivalent)
with open(path) as f:
for line in f:
name, age = line.split()
print(name, age)
os.unlink(path)
Alice 25 Bob 30
Rust v1.99.1
use std::fs;
fn main() {
let path = std::env::temp_dir().join(format!("fsc_rs_{}", std::process::id()));
fs::write(&path, b"Alice 25\nBob 30\n").unwrap();
// Rust has no scanf: read_to_string + lines + split_whitespace + parse
let text = fs::read_to_string(&path).unwrap();
for line in text.lines() {
let mut it = line.split_whitespace();
let name = it.next().unwrap();
let age: i32 = it.next().unwrap().parse().unwrap();
println!("{} {}", name, age);
}
fs::remove_file(&path).unwrap();
}
Alice 25 Bob 30
TypeScript v26.13.1
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
const file = path.join(fs.mkdtempSync(`${os.tmpdir()}/fsc_`), "data.txt");
fs.writeFileSync(file, "Alice 25\nBob 30\n");
// TypeScript has no scanf either: read the file and split each line
const lines = fs.readFileSync(file, "utf8").trim().split("\n");
for (const line of lines) {
const [name, age] = line.split(" ");
console.log(name, age);
}
fs.unlinkSync(file);
Alice 25 Bob 30
Language differences
PHP: fscanf is the file-stream sibling of sscanf (the string version is the A24 sscanf entry): the no-by-reference form returns the parsed array, the by-reference form returns the assigned-field count; format semantics mirror sscanf exactly (see that entry for %s-stops-at-whitespace and related differences); at EOF with nothing parseable it returns false.
C: same-family fscanf(3) prototype: returns the converted-field count; a miss has two states — EOF with zero conversions returns EOF(-1), non-matching input with content returns 0, and the example runs all three branches; %31s width caps prevent buffer overflows.
C++: same as C (<cstdio> keeps the stdio family).
C#: no scanf family — Split + int.Parse is the idiomatic equivalent.
Go: fmt.Fscanf is native but has no %[...] scansets; it returns a (count, error) pair.
Java: no scanf format strings — Scanner takes tokens by delimiter with typed readers like nextInt.
JavaScript/TypeScript: none — read the whole file and split("\n") per line.
Python: no direct counterpart — per-line split() + int(); this IS the mainstream form of "formatted reading" in Python.
Rust: none — lines() + split_whitespace + parse().
Security: same family as sscanf, same format-string attack surface (runaway widths, conversion mismatches) — validate untrusted input against a whitelist before parsing.