crt_printf and ExitProcess in MASM32 with lib - dll

crt_printf, crt_scanf, ExitProcess
Windows 7 with masm32v11r for Environment Path
in .asm file, I'd like to call crt_printf to print (or call ExitProcess to end main procedure). However my code goes with:
.386
.model flat,stdcall
option casemap:none
includelib D:\masm32\lib\msvcrt.lib
printf proto C:dword,:vararg
scanf proto C:dword,:vararg
.DATA
print_int DB "%d",0
print_char DB "%c",0
and my call procedure goes with:
PUSH offset __temp13#_cal#main
PUSH offset print_string
CALL crt_printf
ADD ESP, 8
PUSH _realCock#main
PUSH offset print_int
CALL crt_printf
ADD ESP, 8
PUSH offset __temp14#_cal#main
When I Click the button of build All, messages come with:
Microsoft (R) Macro Assembler Version 6.14.8444
Copyright (C) Microsoft Corp 1981-1997. All rights reserved.
Assembling: D:\masm32\bin\object_code.asm
D:\masm32\bin\object_code.asm(105) : error A2006: undefined symbol : crt_printf
D:\masm32\bin\object_code.asm(109) : error A2006: undefined symbol : crt_printf
D:\masm32\bin\object_code.asm(179) : error A2006: undefined symbol : crt_scanf
D:\masm32\bin\object_code.asm(249) : error A2006: undefined symbol : ExitProcess
Assembly Error
I've struggled with such error for 24 hours, Thx!

crt_printf is a special construct of the MASM32 developers to distiguish it from their macro printf. If you don't include \masm32\macros\macros.asm you don't need this special feature:
.386
.model flat,stdcall
includelib \masm32\lib\msvcrt.lib
includelib \masm32\lib\kernel32.lib
printf proto C :dword, :vararg ; msvcrt
ExitProcess proto STDCALL :DWORD ; kernel32
.DATA
fmt db "%s",10,0
hello db "Hello world!",0
.CODE
main PROC
push OFFSET hello
push OFFSET fmt
call printf
add esp, (2 * 4)
push 0
call ExitProcess
main ENDP
END main
The crt_... aliasses are declared in the msvcrt.inc:
.386
.model flat,stdcall
include \masm32\include\msvcrt.inc
includelib \masm32\lib\msvcrt.lib
includelib \masm32\lib\kernel32.lib
printf proto C :dword, :vararg ; msvcrt
ExitProcess proto STDCALL :DWORD ; kernel32
.DATA
fmt db "%s",10,0
hello db "Hello world!",0
.CODE
main PROC
push OFFSET hello
push OFFSET fmt
call crt_printf
add esp, (2 * 4)
push 0
call ExitProcess
main ENDP
END main
If you want the whole bunch with all declarations and macros then include masm32rt.inc:
include \masm32\include\masm32rt.inc
.DATA
fmt db "%s",10,0
hello db "Hello world!",0
.CODE
main PROC
push OFFSET hello
push OFFSET fmt
call crt_printf
add esp, (2 * 4)
printf ("Hello again: %s\n",OFFSET hello);
push 0
call ExitProcess
main ENDP
END main

Related

How to fix masm32: error LNK2001: unresolved external symbol

I'm creating an app to test an api func IsCharLowerA and then output res using MessageBoxA. I'm using masm32.
link /SUBSYSTEM:WINDOWS kod.obj
Microsoft (R) Incremental Linker Version 5.12.8078
Copyright (C) Microsoft Corp 1992-1998. All rights reserved.
kod.obj : warning LNK4033: converting object format from OMF to COFF
kod.obj : error LNK2001: unresolved external symbol __ExitProcess#4
kod.obj : error LNK2001: unresolved external symbol __MessageBoxA#16
kod.obj : error LNK2001: unresolved external symbol __imp__printf
kod.obj : error LNK2001: unresolved external symbol __imp__scanf
kod.obj : error LNK2001: unresolved external symbol _IsCharLowerA#4
LINK : error LNK2001: unresolved external symbol _WinMainCRTStartup
ml kod.asm
Microsoft (R) Macro Assembler Version 6.14.8444
Copyright (C) Microsoft Corp 1981-1997. All rights reserved.
Assembling: kod.asm
Microsoft (R) Incremental Linker Version 5.12.8078
Copyright (C) Microsoft Corp 1992-1998. All rights reserved.
/z2
"kod.obj"
"kod.exe"
NUL
LINK : warning LNK4044: unrecognized option "z2"; ignored
kod.obj : warning LNK4033: converting object format from OMF to COFF
LINK : fatal error LNK1181: cannot open input file "kod.exe"
I've tried to use microsoft masm32 (to compile code in visual studio), but when the app starts it's only ask for a char and then closes. I could not try to debug due to "source not available" error.
Some code:
.586
.model flat, stdcall
option casemap: none
include C:\masm32\include\windows.inc
include C:\masm32\include\kernel32.inc
include C:\masm32\include\user32.inc
include C:\masm32\include\msvcrt.inc
includelib C:\masm32\lib\msvcrt.lib
includelib C:\masm32\lib\kernel32.lib
includelib C:\masm32\lib\user32.lib
.data
msg db 'Enter char: ', 0
messagebox_title db ' Лабораторна робота № 5 ', 0
result_0 db ' NOT LOWERCASE ', 0
result_1 db ' LOWERCASE ', 0
scan_modifier db '%c', 0
.data?
scan_res dd ?
.code
start:
push ebp
mov ebp, esp
invoke crt_printf, OFFSET msg
invoke crt_scanf, OFFSET scan_modifier, scan_res
push scan_res
call IsCharLowerA
push 0
push offset messagebox_title
cmp eax, 0
jne notNULL
push offset result_0
jmp next
notNULL:
push offset result_1
next:
push 0
call MessageBoxA
push 0
call ExitProcess
pop ebp
end start
Update #1: (changed MessageBoxA -> MessageBoxA#16 and others)
Code:
.586
.model flat, stdcall
option casemap: none
include C:\masm32\include\windows.inc
include C:\masm32\include\kernel32.inc
include C:\masm32\include\user32.inc
include C:\masm32\include\msvcrt.inc
includelib C:\masm32\lib\msvcrt.lib
includelib C:\masm32\lib\kernel32.lib
includelib C:\masm32\lib\user32.lib
extrn MessageBoxA#16 : PROC
extrn ExitProcess#4 : PROC
.data
msg db 'Enter char: ', 0
messagebox_title db ' Лабораторна робота № 5 ', 0
result_0 db ' NOT LOWERCASE ', 0
result_1 db ' LOWERCASE ', 0
scan_modifier db '%c', 0
.data?
scan_res dd ?
.code
start:
push ebp
mov ebp, esp
invoke crt_printf, OFFSET msg
invoke crt_scanf, OFFSET scan_modifier, scan_res
push scan_res
call IsCharLowerA
push 0
push offset messagebox_title
cmp eax, 0
jne notNULL
push offset result_0
jmp next
notNULL:
push offset result_1
next:
push 0
call MessageBoxA#16
push 0
call ExitProcess#4
pop ebp
end start
Res:
link /SUBSYSTEM:WINDOWS kod.obj
Microsoft (R) Incremental Linker Version 5.12.8078
Copyright (C) Microsoft Corp 1992-1998. All rights reserved.
kod.obj : warning LNK4033: converting object format from OMF to COFF
kod.obj : error LNK2001: unresolved external symbol _MessageBoxA#16
kod.obj : error LNK2001: unresolved external symbol __imp__printf
kod.obj : error LNK2001: unresolved external symbol _ExitProcess#4
kod.obj : error LNK2001: unresolved external symbol __imp__scanf
kod.obj : error LNK2001: unresolved external symbol _IsCharLowerA#4
LINK : error LNK2001: unresolved external symbol _WinMainCRTStartup
kod.exe : fatal error LNK1120: 6 unresolved externals
I have a code error LNK2001: unresolved external symbol _MessageBox (uploaded #2 "Final working code") is not succeed linking too
The problems was:
1) For scanf needed OFFSET scan_res, because not value is needed.
2) Can not be compiled using both windows and console subsystem. That's why i used only printfs.
3) Was not enough library msvcrt.
4) Сonverting from OMF to COFF could be ignored.
Working code:
.586
.model flat, stdcall
option casemap: none
include C:\masm32\include\windows.inc
include C:\masm32\include\user32.inc
include C:\masm32\include\msvcrt.inc
includelib C:\masm32\lib\msvcrt.lib
includelib C:\masm32\lib\user32.lib
.data
msg db 'Enter char: ', 0
result_0 db ' NOT LOWERCASE ', 0
result_1 db ' LOWERCASE ', 0
scan_modifier db '%c', 0
.data?
scan_res dd ?
.code
start:
mov ebp, esp
invoke crt_printf, OFFSET msg
invoke crt_scanf, OFFSET scan_modifier, OFFSET scan_res
push scan_res
call IsCharLowerA
cmp eax, 0
jne notNULL
invoke crt_printf, OFFSET result_0
jmp next
notNULL:
invoke crt_printf, OFFSET result_1
next:
ret
end start

How to pass function parameters into inline assembly blocks without assigning them to register variables in c++ [duplicate]

This question already has answers here:
How to access C variable for inline assembly manipulation?
(2 answers)
How to invoke a system call via syscall or sysenter in inline assembly?
(2 answers)
How do I pass inputs into extended asm?
(1 answer)
Closed 3 years ago.
I am trying to write a function, which prints string to stdout without importing <cstdio> or <iostream>.
For this I am trying to pass 2 parameters (const char* and const unsigned) to the asm(...) section in c++ code. And calling write syscall.
This works fine:
void writeInAsm(const char* str, const unsigned len) {
register const char* arg3 asm("rsi") = str;
register const unsigned arg4 asm("rdx") = len;
asm(
"mov rax, 1 ;" // write syscall
"mov rdi, 1 ;" // file descriptor 1 - stdout
"syscall ;"
);
}
Is it possible to do this without those first two lines in which I assign parameters to registers?
Next lines don't work:
mov rsi, str;
// error: relocation R_X86_64_32S against undefined symbol `str' can not be used when making a PIE object; recompile with -fPIC
// compiled with -fPIC - still got this error
mov rsi, [str];
// error: relocation R_X86_64_32S against undefined symbol `str' can not be used when making a PIE object; recompile with -fPIC
// compiled with -fPIC - still got this error
mov rsi, dword ptr str;
// incorrect register `rsi' used with `l' suffix
mov rsi, dword ptr [str];
// incorrect register `rsi' used with `l' suffix
I am compiling with g++ -masm=intel. I am on x86_64 Intel® Core™ i7-7700HQ CPU # 2.80GHz × 8, Ubuntu 19.04 5.0.0-36-generic kernel (if it matters).
$ g++ --version
g++ (Ubuntu 8.3.0-6ubuntu1) 8.3.0
Edit: According to Compiler Explorer, the next can be used:
void writeInAsm(const char* str, const unsigned len) {
asm(
"mov rax, 1 ;"
"mov rdi, 1 ;"
"mov rsi, QWORD PTR [rbp-8] ;"
"mov edx, DWORD PTR [rbp-12] ;"
"syscall ;"
);
}
But is it always rbp register and how will it change with larger number of parameters?

LLDB equivalent of GDB's macros

I have a very useful macro defined in .gdbinit
define rc
call (int)[$arg0 retainCount]
end
Is there anyway to define the same macro for lldb ?
You can do that with the following command definition in lldb:
command regex rc 's/(.+)/print (int)[%1 retainCount]/'
Example:
(lldb) rc indexPath
print (int)[indexPath retainCount]
(int) $2 = 2
You can put that into ~/.lldbinit (and restart Xcode).
One should think that something like
command alias rc print (int)[%1 retainCount]
should work, but as explained in I can't get this simple LLDB alias to work the %1 expansion does not work with expression, and command regex is a workaround.
Incidentally, on architectures where function arguments are passed in registers (x86_64, armv7), lldb defines a series of register aliases that map to the register used to pass the integral values -- arg1, arg2, etc. For instance,
#include <stdio.h>
int main ()
{
char *mytext = "hello world\n";
puts (mytext);
return 0;
}
and we can easily see what argument is passed in to puts without having to remember the ABI conventions,
4 char *mytext = "hello world\n";
-> 5 puts (mytext);
6 return 0;
7 }
(lldb) p mytext
(char *) $0 = 0x0000000100000f54 "hello world\n"
(lldb) br se -n puts
Breakpoint created: 2: name = 'puts', locations = 1, resolved = 1
(lldb) c
Process 2325 resuming
Process 2325 stopped
libsystem_c.dylib`puts:
-> 0x7fff99ce1d9a: pushq %rbp
0x7fff99ce1d9b: movq %rsp, %rbp
0x7fff99ce1d9e: pushq %rbx
0x7fff99ce1d9f: subq $56, %rsp
(lldb) p/x $arg1
(unsigned long) $2 = 0x0000000100000f54
(lldb)
x86_64 and armv7 both pass the first "few" integral values in registers - beyond that they can get stored on the stack or other places and these aliases don't work. lldb doesn't currently provide similar convenience aliases for floating point arguments. But for the most common cases, this is covers what people need.

String length in masm

I try to ouput the string length of hello in cmd screen using the following masm code.
I create a function called strlo to compute string length.
.486
.Model flat,Stdcall
option casemap :none ; case sensitive
include \masm32\include\windows.inc
include \masm32\include\kernel32.inc
includelib \masm32\lib\kernel32.lib
include \masm32\include\masm32.inc
includelib \masm32\lib\masm32.lib
strlo PROTO :DWORD
.data
msg db "Hello",0
.data?
pr dd ?
.code
start:
invoke strlo,addr msg
strlo proc parm:DWORD
xor eax,eax
mov edi,parm
l1:
cmp byte ptr [edi] ,0
je l2
inc edi
inc eax
jmp l1
l2:
ret
strlo endp
invoke StdOut,eax
invoke ExitProcess,0
end start
When I run it, I get no output.
F:\masm32>len.exe
F:\masm32>
One problem is that you have the definition of strlo in the middle of your code. It will execute where it is defined. Instead you should move it to the end and let your main code look like this:
invoke strlo,addr msg
invoke StdOut,eax
invoke ExitProcess,0
Control begins at label "start" because you wrote "end start", then yields at "ret". "invoke StdOut,eax" and "invoke ExitProcess,0" never executed. To ouput the string length of hello in cmd screen you should alter like below:
strlo proc parm:DWORD
...
strlo endp
start:
invoke strlo,addr msg
invoke StdOut,eax
...

File I/O in Every Programming Language [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
This has to be a common question that all programmers have from time to time.
How do I read a line from a text file? Then the next question is always how do i write it back.
Of course most of you use a high level framework in day to day programming (which are fine to use in answers) but sometimes it's nice to know how to do it at a low level too.
I myself know how to do it in C, C++ and Objective-C, but it sure would be handy to see how it's done in all of the popular languages, if only to help us make a better decision about what language to do our file io in. In particular I think it would be interesting to see how its done in the string manipulation languages, like: python, ruby and of course perl.
So I figure here we can create a community resource that we can all star to our profiles and refer to when we need to do file I/O in some new language. Not to mention the exposure we will all get to languages that we don't deal with on a day to day basis.
This is how you need to answer:
Create a new text file called "fileio.txt"
Write the first line "hello" to the text file.
Append the second line "world" to the text file.
Read the second line "world" into an input string.
Print the input string to the console.
Clarification:
You should show how to do this in one programming language per answer only.
Assume that the text file doesn't exist beforehand
You don't need to reopen the text file after writing the first line
No particular limit on the language.
C, C++, C#, Java, Objective-C are all great.
If you know how to do it in Prolog, Haskell, Fortran, Lisp, or Basic then please go right ahead.
LOLCODE
The specs are sketchy to say the least, but I did the best I could. Let the downvoting begin! :) I still find it a fun exercise.
HAI
CAN HAS STDIO?
PLZ OPEN FILE "FILEIO.TXT" ITZ "TehFilez"?
AWSUM THX
BTW #There is no standard way to output to files yet...
VISIBLE "Hello" ON TehFilez
BTW #There isn't a standard way to append to files either...
MOAR VISIBLE "World" ON TehFilez
GIMMEH LINES TehLinez OUTTA TehFilez
I HAS A SecondLine ITZ 1 IN MAH TehLinez
VISIBLE SecondLine
O NOES
VISIBLE "OH NOES!!!"
KTHXBYE
Python 3
with open('fileio.txt', 'w') as f:
f.write('hello')
with open('fileio.txt', 'a') as f:
f.write('\nworld')
with open('fileio.txt') as f:
s = f.readlines()[1]
print(s)
Clarifications
readlines() returns a list of all the lines in the file.
Therefore, the invokation of readlines() results in reading each and every line of the file.
In that particular case it's fine to use readlines() because we have to read the entire file anyway (we want its last line).
But if our file contains many lines and we just want to print its nth line, it's unnecessary to read the entire file.
Here are some better ways to get the nth line of a file in Python: What substitutes xreadlines() in Python 3?.
What is this with statement?
The with statement starts a code block where you can use the variable f as a stream object returned from the call to open().
When the with block ends, python calls f.close() automatically.
This guarantees the file will be closed when you exit the with block no matter how or when you exit the block
(even if you exit it via an unhandled exception). You could call f.close() explicitly, but what if your code raises an exception and you don't get to the f.close() call? That's why the with statement is useful.
You don't need to reopen the file before each operation. You can write the whole code inside one with block.
with open('fileio.txt', 'w+') as f:
f.write('hello')
f.write('\nworld')
s = f.readlines()[1]
print(s)
I used three with blocks to emphsize the difference between the three operations:
write (mode 'w'), append (mode 'a'), read (mode 'r', the default).
Brain***k
,------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<<->>>->>>>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<->>>->>>>[-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<[-]+<[-]+<<<<<<[>>>>>>[-]<<<<<<[-]]>>>>>>[[-]+<<<<<[>>>>>[-]<<<<<[-]]>>>>>[[-]+<<<<[>>>>[-]<<<<[-]]>>>>[[-]+<<<[>>>[-]<<<[-]]>>>[[-]+<<[>>[-]<<[-]]>>[[-]+<[>[-]<[-]]>[[-]+++++++++++++++++++++++++++++++++++++++++++++++++.-...>[-]<[-]]<>[-]]<<>>[-]]<<<>>>[-]]<<<<>>>>[-],------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<<->>>->>>>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>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]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<<[>>[-]<<[-]]>>[[-]+>[<[-]>[-]]<[<<<<<<<<[-]<+>>>>>>>>>[-]]><[-]]<<<<<<<<<++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>>>>>>>>[-]]
COBOL
Since nobody else did......
IDENTIFICATION DIVISION.
PROGRAM-ID. WriteDemo.
AUTHOR. Mark Mullin.
* Hey, I don't even have a cobol compiler
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT StudentFile ASSIGN TO "STUDENTS.DAT"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD TestFile.
01 TestData.
02 LineNum PIC X.
02 LineText PIC X(72).
PROCEDURE DIVISION.
Begin.
OPEN OUTPUT TestFile
DISPLAY "This language is still around."
PERFORM GetFileDetails
PERFORM UNTIL TestData = SPACES
WRITE TestData
PERFORM GetStudentDetails
END-PERFORM
CLOSE TestFile
STOP RUN.
GetFileDetails.
DISPLAY "Enter - Line number, some text"
DISPLAY "NXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
ACCEPT TestData.
Haskell
main :: IO ()
main = let filePath = "fileio.txt" in
do writeFile filePath "hello"
appendFile filePath "\nworld"
fileLines <- readFile filePath
let secondLine = (lines fileLines) !! 1
putStrLn secondLine
If you just want to read/write a file:
main :: IO ()
main = readFile "somefile.txt" >>= writeFile "someotherfile.txt"
D
module d_io;
import std.stdio;
void main()
{
auto f = File("fileio.txt", "w");
f.writeln("hello");
f.writeln("world");
f.open("fileio.txt", "r");
f.readln;
auto s = f.readln;
writeln(s);
}
Ruby
PATH = 'fileio.txt'
File.open(PATH, 'w') { |file| file.puts "hello" }
File.open(PATH, 'a') { |file| file.puts "world" }
puts line = File.readlines(PATH).last
C#
string path = "fileio.txt";
File.WriteAllLines(path, new[] { "hello"}); //Will end it with Environment.NewLine
File.AppendAllText(path, "world");
string secondLine = File.ReadLines(path).ElementAt(1);
Console.WriteLine(secondLine);
File.ReadLines(path).ElementAt(1) is .Net 4.0 only, the alternative is File.ReadAllLines(path)[1] which parses the whole file into an array.
ANSI C
#include <stdio.h>
#include <stdlib.h>
int /*ARGSUSED*/
main(char *argv[0], int argc) {
FILE *file;
char buf[128];
if (!(file = fopen("fileio.txt", "w")) {
perror("couldn't open for writing fileio.txt");
exit(1);
}
fprintf(file, "hello");
fclose(file);
if (!(file = fopen("fileio.txt", "a")) {
perror("couldn't opened for appening fileio.txt");
exit(1);
}
fprintf(file, "\nworld");
fclose(file);
if (!(file = fopen("fileio.txt", "r")) {
perror("couldn't open for reading fileio.txt");
exit(1);
}
fgets(buf, sizeof(buf), file);
fgets(buf, sizeof(buf), file);
fclose(file);
puts(buf);
return 0;
}
Shell Script (UNIX)
#!/bin/sh
echo "hello" > fileio.txt
echo "world" >> fileio.txt
LINE=`sed -ne2p fileio.txt`
echo $LINE
Actually the sed -n "2p" part prints the second line, but the question asks for the second line to be stored in a variable and then printed, so... :)
x86 Assembler (NASM) on Linux
I haven't touched asm in 7 years, so I had to use google a bit to hack this together, but still, it works ;) I know it's not 100% correct, but hey :D
OK, it doesn't work. sorry bout this. while it does print world in the end, it doesn't print it from the file, but from the ecx which is set on line 27.
section .data
hello db 'hello',10
helloLen equ $-hello
world db 'world',10
worldLen equ $-world
helloFile db 'hello.txt'
section .text
global _start
_start:
mov eax,8
mov ebx,helloFile
mov ecx,00644Q
int 80h
mov ebx,eax
mov eax,4
mov ecx, hello
mov edx, helloLen
int 80h
mov eax,4
mov ecx, world
mov edx, worldLen
int 80h
mov eax,6
int 80h
mov eax,5
mov ebx,helloFile
int 80h
mov eax,3
int 80h
mov eax,4
mov ebx,1
int 80h
xor ebx,ebx
mov eax,1
int 80h
References used:
http://www.cin.ufpe.br/~if817/arquivos/asmtut/quickstart.html
http://bluemaster.iu.hio.no/edu/dark/lin-asm/syscalls.html
http://www.digilife.be/quickreferences/QRC/LINUX%20System%20Call%20Quick%20Reference.pdf
JavaScript - node.js
First, lots of nested callbacks.
var fs = require("fs");
var sys = require("sys");
var path = "fileio.txt";
fs.writeFile(path, "hello", function (error) {
fs.open(path, "a", 0666, function (error, file) {
fs.write(file, "\nworld", null, "utf-8", function () {
fs.close(file, function (error) {
fs.readFile(path, "utf-8", function (error, data) {
var lines = data.split("\n");
sys.puts(lines[1]);
});
});
});
});
});
A little bit cleaner:
var writeString = function (string, nextAction) {
fs.writeFile(path, string, nextAction);
};
var appendString = function (string, nextAction) {
return function (error, file) {
fs.open(path, "a", 0666, function (error, file) {
fs.write(file, string, null, "utf-8", function () {
fs.close(file, nextAction);
});
});
};
};
var readLine = function (index, nextAction) {
return function (error) {
fs.readFile(path, "utf-8", function (error, data) {
var lines = data.split("\n");
nextAction(lines[index]);
});
};
};
var writeToConsole = function (line) {
sys.puts(line);
};
writeString("hello", appendString("\nworld", readLine(1, writeToConsole)));
Common Lisp
(defun main ()
(with-open-file (s "fileio.txt" :direction :output :if-exists :supersede)
(format s "hello"))
(with-open-file (s "fileio.txt" :direction :io :if-exists :append)
(format s "~%world")
(file-position s 0)
(loop repeat 2 for line = (read-line s nil nil) finally (print line))))
PowerShell
sc fileio.txt 'hello'
ac fileio.txt 'world'
$line = (gc fileio.txt)[1]
$line
Shell Script
Here's a shell script using just builtin commands, rather than invoking external commands such as sed or tail as previous responses have done.
#!/bin/sh
echo hello > fileio.txt # Print "hello" to fileio.txt
echo world >> fileio.txt # Print "world" to fileio.txt, appending
# to what is already there
{ read input; read input; } < fileio.txt
# Read the first two lines of fileio.txt,
# storing the second in $input
echo $input # Print the contents of $input
When writing significant shell scripts, it is advisable to use builtins as much as possible, since spawning a separate process can be slow; from a quick test on my machine, the sed solution is about 20 times slower than using read. If you're going to call sed once, as in this case, it doesn't really matter much, as it will execute more quickly than you can notice, but if you're going to execute it hundreds or thousands of times, it can add up.
For those unfamiliar with the syntax, { and } execute a list of commands in the current shell environment (as opposed to ( and ) which create a subshell; we need to be operating in the current shell environment, so we can use the value of the variable later). We need to group the commands together in order to have them both operate on the same input stream, created by redirecting from fileio.txt; if we simply ran read < fileio.txt; read input < fileio.txt, we would just get the first line, as the file would be closed and re-opened between the two commands. Due to an idiosyncrasy of shell syntax ({ and } are reserved words, as opposed to metacharacters), we need to separate the { and } from the rest of the commands with spaces, and terminate the list of commands with a ;.
The read builtin takes as an argument the names of variables to read into. It consumes a line of input, breaks the input by whitespace (technically, it breaks it according to the contents of $IFS, which defaults to a space character, where a space character means split it on any of space, tab, or newline), assigns each word to the variable names given in order, and assigns the remainder of the line to the last variable. Since we're just supplying one variable, it just puts the whole line in that variable. We reuse the $input variable, since we don't care what's on the first line (if we're using Bash we could just not supply a variable name, but to be portable, you must always supply at least one name).
Note that while you can read lines one at a time, like I do here, a much more common pattern would be to wrap it in a while loop:
while read foo bar baz
do
process $foo $bar $baz
done < input.txt
Clojure
(use '[clojure.java.io :only (reader)])
(let [file-name "fileio.txt"]
(spit file-name "hello")
(spit file-name "\nworld" :append true)
(println (second (line-seq (reader file-name)))))
Or equivalently, using the threading macro -> (also known as the paren remover):
(use '[clojure.java.io :only (reader)])
(let [file-name "fileio.txt"]
(spit file-name "hello")
(spit file-name "\nworld" :append true)
(-> file-name reader line-seq second println))
F#
let path = "fileio.txt"
File.WriteAllText(path, "hello")
File.AppendAllText(path, "\nworld")
let secondLine = File.ReadLines path |> Seq.nth 1
printfn "%s" secondLine
BASIC
I haven't used BASIC in almost 10 years, but this question gave me a reason to quickly brush up my knowledge. :)
OPEN "fileio.txt" FOR OUTPUT AS 1
PRINT #1, "hello"
PRINT #1, "world"
CLOSE 1
OPEN "fileio.txt" FOR INPUT AS 1
LINE INPUT #1, A$
LINE INPUT #1, A$
CLOSE 1
PRINT A$
Objective-C
NSFileHandle *fh = [NSFileHandle fileHandleForUpdatingAtPath:#"fileio.txt"];
[[NSFileManager defaultManager] createFileAtPath:#"fileio.txt" contents:nil attributes:nil];
[fh writeData:[#"hello" dataUsingEncoding:NSUTF8StringEncoding]];
[fh writeData:[#"\nworld" dataUsingEncoding:NSUTF8StringEncoding]];
NSArray *linesInFile = [[[NSString stringWithContentsOfFile:#"fileio.txt"
encoding:NSUTF8StringEncoding
error:nil] stringByStandardizingPath]
componentsSeparatedByString:#"\n"];
NSLog(#"%#", [linesInFile objectAtIndex:1]);
Perl
#!/usr/bin/env perl
use 5.10.0;
use utf8;
use strict;
use autodie;
use warnings qw< FATAL all >;
use open qw< :std :utf8 >;
use English qw< -no_match_vars >;
# and the last shall be first
END { close(STDOUT) }
my $filename = "fileio.txt";
my($handle, #lines);
$INPUT_RECORD_SEPARATOR = $OUTPUT_RECORD_SEPARATOR = "\n";
open($handle, ">", $filename);
print $handle "hello";
close($handle);
open($handle, ">>", $filename);
print $handle "world";
close($handle);
open($handle, "<", $filename);
chomp(#lines = <$handle>);
close($handle);
print STDOUT $lines[1];
R:
cat("hello\n", file="fileio.txt")
cat("world\n", file="fileio.txt", append=TRUE)
line2 = readLines("fileio.txt", n=2)[2]
cat(line2)
PHP
<?php
$filePath = "fileio.txt";
file_put_contents($filePath, "hello");
file_put_contents($filePath, "\nworld", FILE_APPEND);
$lines = file($filePath);
echo $lines[1];
// closing PHP tags are bad practice in PHP-only files, don't use them
Java
import java.io.*;
import java.util.*;
class Test {
public static void main(String[] args) throws IOException {
String path = "fileio.txt";
File file = new File(path);
//Creates New File...
try (FileOutputStream fout = new FileOutputStream(file)) {
fout.write("hello\n".getBytes());
}
//Appends To New File...
try (FileOutputStream fout2 = new FileOutputStream(file,true)) {
fout2.write("world\n".getBytes());
}
//Reading the File...
try (BufferedReader fin = new BufferedReader(new FileReader(file))) {
fin.readLine();
System.out.println(fin.readLine());
}
}
}
C++
#include <limits>
#include <string>
#include <fstream>
#include <iostream>
int main() {
std::fstream file( "fileio.txt",
std::ios::in | std::ios::out | std::ios::trunc );
file.exceptions( std::ios::failbit );
file << "hello\n" // << std::endl, not \n, if writing includes flushing
<< "world\n";
file.seekg( 0 )
.ignore( std::numeric_limits< std::streamsize >::max(), '\n' );
std::string input_string;
std::getline( file, input_string );
std::cout << input_string << '\n';
}
or somewhat less pedantically,
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int main() {
fstream file( "fileio.txt", ios::in | ios::out | ios::trunc );
file.exceptions( ios::failbit );
file << "hello" << endl
<< "world" << endl;
file.seekg( 0 ).ignore( 10000, '\n' );
string input_string;
getline( file, input_string );
cout << input_string << endl;
}
Go
package main
import (
"os"
"bufio"
"log"
)
func main() {
file, err := os.Open("fileio.txt", os.O_RDWR | os.O_CREATE, 0666)
if err != nil {
log.Exit(err)
}
defer file.Close()
_, err = file.Write([]byte("hello\n"))
if err != nil {
log.Exit(err)
}
_, err = file.Write([]byte("world\n"))
if err != nil {
log.Exit(err)
}
// seek to the beginning
_, err = file.Seek(0,0)
if err != nil {
log.Exit(err)
}
bfile := bufio.NewReader(file)
_, err = bfile.ReadBytes('\n')
if err != nil {
log.Exit(err)
}
line, err := bfile.ReadBytes('\n')
if err != nil {
log.Exit(err)
}
os.Stdout.Write(line)
}
Erlang
Probably not the most idiomatic Erlang, but:
#!/usr/bin/env escript
main(_Args) ->
Filename = "fileio.txt",
ok = file:write_file(Filename, "hello\n", [write]),
ok = file:write_file(Filename, "world\n", [append]),
{ok, File} = file:open(Filename, [read]),
{ok, _FirstLine} = file:read_line(File),
{ok, SecondLine} = file:read_line(File),
ok = file:close(File),
io:format(SecondLine).
Emacs Lisp
Despite what some people say Emacs is mainly a text editor [1]. So while Emacs Lisp can be used to solve all kinds of problems it is optimized towards the needs of a text editor. Since text editors (obviously) have quite specific needs when it comes to how files are handled this affects what file related functionality Emacs Lisp offers.
Basically this means that Emacs Lisp does not offer functions to open a file as a stream, and read it part by part. Likewise you can't append to a file without loading the whole file first. Instead the file is completely [2] read into a buffer [3], edited and then saved to a file again.
For must tasks you would use Emacs Lisp for this is suitable and if you want to do something that does not involve editing the same functions can be used.
If you want to append to a file over and over again this comes with a huge overhead, but it is possible as demonstrated here. In practice you normally finish making changes to a buffer whether manually or programmatically before writing to a file (just combine the first two s-expressions in the example below).
(with-temp-file "file"
(insert "hello\n"))
(with-temp-file "file"
(insert-file-contents "file")
(goto-char (point-max))
(insert "world\n"))
(with-temp-buffer
(insert-file-contents "file")
(next-line)
(message "%s" (buffer-substring (point) (line-end-position))))
[1] At least I would not go as far as calling it an OS; an alternative UI yes, an OS no.
[2] You can load only parts of a file, but this can only be specified byte-wise.
[3] A buffer is both a datatype in someways similar to a string as well as the "thing you see while editing a file". While editing a buffer is displayed in a window but buffers do not necessarily have to be visible to the user.
Edit: If you want to see the text being inserted into the buffer you obviously have to make it visible, and sleep between actions. Because Emacs normally only redisplays the screen when waiting for user input (and sleeping ain't the same as waiting for input) you also have to force redisplay. This is necessary in this example (use it in place of the second sexp); in practice I never had to use `redisplay' even once - so yes, this is ugly but ...
(with-current-buffer (generate-new-buffer "*demo*")
(pop-to-buffer (current-buffer))
(redisplay)
(sleep-for 1)
(insert-file-contents "file")
(redisplay)
(sleep-for 1)
(goto-char (point-max))
(redisplay)
(sleep-for 1)
(insert "world\n")
(redisplay)
(sleep-for 1)
(write-file "file"))
Windows Batch Files - Version #2
#echo off
echo hello > fileio.txt
echo world >> fileio.txt
set /P answer=Insert:
echo %answer% >> fileio.txt
for /f "skip=1 tokens=*" %%A in (fileio.txt) do echo %%A
To explain that last horrible looking for loop, it assumes that there is only hello (newline) world in the file. So it just skips the first line and echos only the second.
Changelog
2 - Opps, must of misread the requirements or they changed on me. Now reads last line from file
Scala:
Using standard library:
val path = "fileio.txt"
val fout = new FileWriter(path)
fout write "hello\n"
fout.close()
val fout0 = new FileWriter(path, true)
fout0 write "world\n"
fout0.close()
val str = Source.fromFile(path).getLines.toSeq(1)
println(str)
Using Josh Suereth's Scala-ARM Library:
val path = "fileio.txt"
for(fout <- managed(new FileWriter(path)))
fout write "hello\n"
for(fout <- managed(new FileWriter(path, true)))
fout write "world\n"
val str = Source.fromFile(path).getLines.toSeq(1)
println(str)
Since many people have used the same file descriptor to write the two strings, I'm also including that way in my answer.
Using standard library:
val path = "fileio.txt"
val fout = new FileWriter(path)
fout write "hello\n"
fout write "world\n"
fout.close()
val str = Source.fromFile(path).getLines.toSeq(1)
println(str)
Using Josh Suereth's Scala-ARM Library:
val path = "fileio.txt"
for(fout <- managed(new FileWriter(path))){
fout write "hello\n"
fout write "world\n"
}
val str = Source.fromFile(path).getLines.toSeq(1)
println(str)
Groovy
new File("fileio.txt").with {
write "hello\n"
append "world\n"
println secondLine = readLines()[1]
}