D Snippet: Reading a file to standard output on Windows Operating System. (FileScan.d)

BoQsc vaidas.boqsc at gmail.com
Sat Dec 9 08:51:39 UTC 2023


#### `switch` statement to match a text line
While outputing to the standard stream, it is also possible to 
use `switch` statement to **match a text line to a text line in a 
file.** I personally think it improve readability and 
maintainability in some applications.

```
import std;

void main(){

	foreach (line; File("example.txt").byLine(No.keepTerminator, 
"\r\n")){
		switch(line) {
		   case "   HelloWorld"  :
			  writeln("|"~line~"|");
			  writeln("^This Line is here.");
			  break;

		   default :
			writeln("|"~line~"|");
		}
	}
}
```

#### Reading file, matching line, changing the line, outputting 
to both: to a standard stream and another file; line by line

In this snippet, we are not only reading a file, editing its 
output and outputting to the standard output stream, but also try 
to save changes on another file: filling it with the edited 
output.

```
import std;

void main(){

	File edit = File("example2.txt", "w");
	foreach (line; File("example.txt").byLine(No.keepTerminator, 
"\r\n")){
		switch(line) {
		   case "   HelloWorld":
			  edit.write("RandomWord\n");
			  writeln("|"~"RandomWord"~"|");
			  break;

		   default :
			edit.write(line ~ "\n");
			writeln("|" ~ line ~ "|");
		}
	}
	edit.close;
}
```

**Inputs:**
**Example.txt**

```
test
  s

    HelloWorld
t
ff

```


**Outputs:**
**stdout:**
```
|test|
| s|
| |
|RandomWord|
|t|
|ff|
```

**Example2.txt**
```
test
  s

RandomWord
t
ff

```


More information about the Digitalmars-d-learn mailing list