我正在尝试创建一个程序,该程序创建一个新文件并将现有文件的内容复制到其中。我能够打开读取原始文件的内容并将其写入内存,但是当将内存内容写入新文件时,会发生分段错误。
section .data
openFile: db 'file1.txt', 0 ; Source file to open for reading
fileModeR: db 'r', 0 ; File mode for reading
writeFile: db 'file2.txt', 0 ; Destination file to open for writing
fileModeW: db 'w', 0 ; File mode for writing
section .bss
fileHandleR resd 1 ; To store the file descriptor for reading
fileHandleW resd 1 ; To store the file descriptor for writing
buffer resb 1 ; Reserve buffer for one character
section .text
extern fopen, fgetc, fputc, fclose
global main
main:
; Open source file for reading
push fileModeR ; Push read mode
push openFile ; Push file name
call fopen
add esp, 8
mov [fileHandleR], eax ; Store the file handle
test eax, eax ; Check for null
jz exit_program ; Exit if fopen failed
; Open destination file for writing
push fileModeW ; Push write mode
push writeFile ; Push file name
call fopen
add esp, 8
mov [fileHandleW], eax ; Store the file handle
test eax, eax ; Check for null
jz close_source ; Close source file and exit if fopen failed
; Read from file1.txt and write to file2.txt
copy_loop:
mov eax, [fileHandleR] ; Load the file pointer into eax
push eax ; Push the file pointer onto the stack
call fgetc ; Read a character
add esp, 4 ; Clean up the stack after the call
test eax, eax ; Test for EOF or error
js close_files ; If sign flag is set, hit EOF or error
mov ecx, eax ; Move the character into ecx to use later with fputc
mov eax, [fileHandleW] ; Move file handle for writing into eaxn
push ecx ; Push the character to write
push eax ; Push the file handle for writing
call fputc ; Write the character
add esp, 8 ; Clean up the stack
test eax, eax ; Test for fputc success
js close_files ; If sign flag is set, an error occurred
jmp copy_loop ; Repeat the loop
close_files:
mov eax, [fileHandleW] ; Get the file handle for writing
push eax ; Push it to fclose
call fclose ; Close file2.txt
add esp, 4 ; Clean up the stack
close_source:
mov eax, [fileHandleR] ; Get the file handle for reading
push eax ; Push it to fclose
call fclose ; Close file1.txt
add esp, 4 ; Clean up the stack
exit_program:
; Exit the program
mov eax, 1 ; syscall number for exit
xor ebx, ebx ; return 0 status
int 0x80 ; call kernel
错误发生在调用 fputc 时,我相信分段错误发生在
fputc
调用期间,表明文件句柄(应该是 FILE*
指针)未被 正确识别fputc
。我是装配新手,我不明白为什么要这样做。我已附上 gdb 的屏幕截图,我可以看到一切似乎都在正常工作,直到 fputc 例如包含正确值的 ecx 和包含文件处理程序的 eax
fputc
希望字符作为第一个参数,FILE*
作为第二个参数。这意味着它们应该以相反的顺序推送(因为这就是堆栈的工作原理,最后一个首先被取出。
因此,您应该先按
EAX
,然后按ECX
,以便按正确的顺序读取它们。