Advanced

File I/O

BanglaCode provides built-in functions for reading and writing files:poro (read) and lekho (write).

Reading Files (poro)

The poro function (meaning "read") reads the entire content of a file:

1// Read a text file
2dhoro content = poro("data.txt");
3dekho(content);
4
5// Read and process line by line
6dhoro lines = bhag(content, "\n");
7ghuriye (dhoro i = 0; i < dorghyo(lines); i = i + 1) {
8 dekho("Line", i + 1, ":", lines[i]);
9}

Reading JSON Files

1// Read JSON file
2dhoro jsonStr = poro("config.json");
3dhoro config = json_poro(jsonStr);
4
5dekho("App name:", config.name);
6dekho("Version:", config.version);

Error Handling for File Reading

1chesta {
2 dhoro content = poro("myfile.txt");
3 dekho("File content:", content);
4} dhoro_bhul (error) {
5 dekho("Could not read file:", error);
6}
7
8// Check if file exists by attempting to read
9kaj fileExists(path) {
10 chesta {
11 poro(path);
12 ferao sotti;
13 } dhoro_bhul (e) {
14 ferao mittha;
15 }
16}
17
18jodi (fileExists("data.txt")) {
19 dekho("File exists!");
20} nahole {
21 dekho("File not found");
22}

Writing Files (lekho)

The lekho function (meaning "write") writes content to a file:

1// Write text to file
2lekho("output.txt", "Hello, World!");
3
4// Write multiple lines
5dhoro content = "Line 1\nLine 2\nLine 3";
6lekho("multiline.txt", content);
7
8// Write from array
9dhoro lines = ["First line", "Second line", "Third line"];
10lekho("fromarray.txt", joro(lines, "\n"));

Writing JSON Data

1dhoro data = {
2 users: [
3 {naam: "Rahim", boyosh: 25},
4 {naam: "Karim", boyosh: 30}
5 ],
6 count: 2,
7 lastUpdated: somoy()
8};
9
10// Convert to JSON and write
11dhoro jsonStr = json_banao(data);
12lekho("users.json", jsonStr);
13
14dekho("Data saved to users.json");

Appending to Files

1// BanglaCode overwrites by default
2// To append, read first then write combined content
3
4kaj appendToFile(path, newContent) {
5 dhoro existing = "";
6
7 chesta {
8 existing = poro(path);
9 } dhoro_bhul (e) {
10 // File doesn't exist, start fresh
11 existing = "";
12 }
13
14 lekho(path, existing + newContent);
15}
16
17// Usage
18appendToFile("log.txt", "New log entry\n");
19appendToFile("log.txt", "Another entry\n");

Practical Examples

CSV Processing

1// Read CSV file
2dhoro csvContent = poro("data.csv");
3dhoro lines = bhag(csvContent, "\n");
4
5// Parse header
6dhoro header = bhag(lines[0], ",");
7dekho("Columns:", header);
8
9// Parse data rows
10dhoro data = [];
11ghuriye (dhoro i = 1; i < dorghyo(lines); i = i + 1) {
12 jodi (dorghyo(lines[i]) > 0) {
13 dhoro values = bhag(lines[i], ",");
14 dhoro row = {};
15
16 ghuriye (dhoro j = 0; j < dorghyo(header); j = j + 1) {
17 row[header[j]] = values[j];
18 }
19
20 dhokao(data, row);
21 }
22}
23
24// Use parsed data
25dekho("Total rows:", dorghyo(data));
26ghuriye (dhoro i = 0; i < dorghyo(data); i = i + 1) {
27 dekho(data[i]);
28}

Writing CSV

1dhoro users = [
2 {naam: "Rahim", boyosh: 25, city: "Dhaka"},
3 {naam: "Karim", boyosh: 30, city: "Chittagong"},
4 {naam: "Jamil", boyosh: 28, city: "Sylhet"}
5];
6
7// Build CSV
8dhoro header = "naam,boyosh,city";
9dhoro rows = [header];
10
11ghuriye (dhoro i = 0; i < dorghyo(users); i = i + 1) {
12 dhoro u = users[i];
13 dhokao(rows, u.naam + "," + lipi(u.boyosh) + "," + u.city);
14}
15
16dhoro csv = joro(rows, "\n");
17lekho("users.csv", csv);
18
19dekho("Saved to users.csv");

Log File

1kaj log(message, level) {
2 jodi (level == khali) {
3 level = "INFO";
4 }
5
6 // Format: [TIMESTAMP] [LEVEL] message
7 dhoro timestamp = somoy();
8 dhoro entry = "[" + lipi(timestamp) + "] [" + level + "] " + message + "\n";
9
10 // Append to log file
11 dhoro existing = "";
12 chesta {
13 existing = poro("app.log");
14 } dhoro_bhul (e) {
15 existing = "";
16 }
17
18 lekho("app.log", existing + entry);
19}
20
21// Usage
22log("Application started");
23log("Processing data...");
24log("Something looks wrong", "WARN");
25log("Critical failure!", "ERROR");

Configuration File

1dhoro CONFIG_FILE = "config.json";
2
3kaj loadConfig() {
4 chesta {
5 dhoro content = poro(CONFIG_FILE);
6 ferao json_poro(content);
7 } dhoro_bhul (e) {
8 dekho("Config not found, using defaults");
9 ferao {
10 theme: "dark",
11 language: "bn",
12 fontSize: 14
13 };
14 }
15}
16
17kaj saveConfig(config) {
18 dhoro json = json_banao(config);
19 lekho(CONFIG_FILE, json);
20 dekho("Config saved");
21}
22
23// Usage
24dhoro config = loadConfig();
25dekho("Current theme:", config.theme);
26
27// Update config
28config.theme = "light";
29saveConfig(config);

Data Backup

1kaj backup(sourcePath, backupDir) {
2 chesta {
3 // Read source file
4 dhoro content = poro(sourcePath);
5
6 // Create backup filename with timestamp
7 dhoro timestamp = somoy();
8 dhoro backupPath = backupDir + "/backup_" + lipi(timestamp) + ".txt";
9
10 // Write backup
11 lekho(backupPath, content);
12
13 dekho("Backup created:", backupPath);
14 ferao sotti;
15 } dhoro_bhul (error) {
16 dekho("Backup failed:", error);
17 ferao mittha;
18 }
19}
20
21// Create backup
22backup("important_data.txt", "backups");

Simple Database

1dhoro DB_FILE = "database.json";
2
3kaj loadDB() {
4 chesta {
5 dhoro content = poro(DB_FILE);
6 ferao json_poro(content);
7 } dhoro_bhul (e) {
8 ferao {users: [], nextId: 1};
9 }
10}
11
12kaj saveDB(db) {
13 lekho(DB_FILE, json_banao(db));
14}
15
16kaj addUser(naam, email) {
17 dhoro db = loadDB();
18
19 dhoro user = {
20 id: db.nextId,
21 naam: naam,
22 email: email,
23 createdAt: somoy()
24 };
25
26 dhokao(db.users, user);
27 db.nextId = db.nextId + 1;
28
29 saveDB(db);
30 ferao user;
31}
32
33kaj findUser(id) {
34 dhoro db = loadDB();
35
36 ghuriye (dhoro i = 0; i < dorghyo(db.users); i = i + 1) {
37 jodi (db.users[i].id == id) {
38 ferao db.users[i];
39 }
40 }
41
42 ferao khali;
43}
44
45// Usage
46dhoro newUser = addUser("Rahim", "rahim@example.com");
47dekho("Created user:", newUser);
48
49dhoro found = findUser(1);
50dekho("Found user:", found);

Best Practices

  • Always handle errors - Files might not exist or be inaccessible
  • Use relative paths carefully - Consider the working directory
  • Close resources in finally - Though BanglaCode handles this automatically
  • Validate before writing - Ensure data is valid before persisting
  • Create backups - Before overwriting important files