Example: Working with files and standard input
The follwing system functions and file functions can be used to work with the standard input and files.
<?v1
// Read single character from input
c = getch ();
print (c);
// Read single character from input as keyboard/ascii number
c = getch (true);
print (c);
// Read line from input with text message
result = input ("Type in something: ");
print ("You typed in: ", result);
// If console is off, keyboard input will not be shown
console_echo (0);
result = input ("Type in some secret: ");
print ("\r\nYou typed in: ", result);
?>
<?v1
// Read file data from standard input
// Example: v1 script.v1 < file.dat
fh = fopen ("v1://stdin");
print ("Input size: ", filesize (fh));
pos = 0;
while (!feof (fh)) {
line = fgets (fh);
print ("Pos ", pos, "\t: ", line);
pos=ftell(fh);
}
?>
<?v1
// Read file line by line
if (fh = fopen ("myfile.txt")) {
line = "";
while (freadln (fh, line)) {
tokens = explode (";", line);
print_r (tokens);
}
fclose (fh);
}
?>
<?v1
// Read a file in blocks (default block size is 64 KB)
if (fh = fopen ("myfile.bin")) {
block = "";
while (bytesRead=fread (fh, block)) {
printf ("Block of %u bytes read", bytesRead);
// Do something with the block
// ...
}
fclose (fh);
}
?>
<?v1
// Create a file and write binary data
if (fh = fopen ("myfile.txt", "w+")) {
binary = "\x56\x31\x20\x53\x63\x72\x69\x70\x74\0"; // Binary representation of V1 Script with zero byte
binary.=binformat (42, 4); // Add 42 as 64 Bit binary number
binary.=binformat (42, 3); // Add 42 as 32 Bit binary number
binary.=binformat (42); // Add 42 as binary number with system byte alignment (4 on 32 Bit, 8 on 64 Bit versions of V1)
fwrite (fh, binary);
fclose (fh);
}
?>
<?v1
// Read a file from specific position
if (fh = fopen ("myfile.txt", "r")) {
fseek (fh, 3); // Set file pointer
c = "";
fread (fh, c, 1); // Read 1 Byte
print (c);
fclose (fh);
}
?>