【发布时间】:2018-05-06 18:31:27
【问题描述】:
我需要翻转文件的行顺序并将它们写入另一个文件,但我有一些问题。由于某种原因我无法在 file2 中写入...任何建议和提示都会很有用,这是我的第一个问题这种类型的。我老师的一个提示是使用 fseek,我使用了它,但我卡住了。
示例:
输入文件1:
line1
line 2
line 3
所需的输出文件2:
line 3
line2
line 1
.386
.model flat, stdcall
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;includem biblioteci, si declaram ce functii vrem sa importam
includelib msvcrt.lib
extern exit: proc
extern fopen:proc
extern getc:proc
extern fclose:proc
extern printf:proc
extern ftell:proc
extern fseek:proc
extern fscanf:proc
extern fprintf: proc
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;declaram simbolul start ca public - de acolo incepe executia
public start
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;sectiunile programului, date, respectiv cod
.data
;aici declaram date
s db 99 dup(0)
read db "r",0
write db "w",0
nume db "fisier1.txt",0
nume2 db "fisier2.txt",0
seek_end dd 2
format db "%s",0
.code
start:
;open first file to read
push offset read
push offset nume
call fopen
add esp,8
mov esi,eax;save pointer of file
;open second file to write
push offset write
push offset nume2
call fopen
add esp,8
mov edi,eax;save pointer of file
;find the end of file
push seek_end
push -1
push esi
call fseek
add esp,12
;save in ecx current position
push esi
call ftell
add esp,4
mov ecx,eax
et:
push esi
call getc
add esp,4
cmp eax,0ah;verify if isn't new line
jne previous
previous:
;move to the previous line
push 1
push -1
push esi
call fseek
add esp,12
jmp cont
read_write:
;read the line in string s
push offset s
push offset format
push esi
call fscanf
add esp,12
;print string s in second file
push offset s
push offset format
push edi
call fprintf
add esp,12
jmp previous
cont:
dec ecx
;verify if isn't the beginning of file
cmp ecx,0
jne et
push 0
call exit
end start
【问题讨论】:
-
那么当你运行这个程序时会发生什么?
fisier2.txt是由您的第二个fopen函数调用创建的,对吗?然后你寻找输入文件的输入并尝试从那里读取,返回 EOF 因为你在最后。此外,ECX 是您正在使用的调用约定中的一个调用破坏寄存器,因此希望每个库call销毁它。使用ebx作为您的柜台或其他东西。无论如何,这不是minimal reproducible example,因为您还没有展示会发生什么。 idownvotedbecau.se/nodebugging -
您的老师使用
lseek的提示可能是使用它来查找文件的长度以找出您需要多大的缓冲区,然后回到开头。然后读取整个输入文件,并在缓冲区上向后循环,找到换行符时打印行。 -
对不起,老师的提示是 fseek,文件创建成功,从 file1 读取没问题,但由于某种原因写入 file2 不起作用
-
fseek更有意义,因为您正在使用其他 C stdio 函数,并且 fseek 到末尾 +ftell是查找文件长度的唯一 ISO C 方法。但是不要忘记fseek回到开头。如果您有lseek可用,您将使用stat或fstat。无论如何,使用调试器来找出在您单步执行程序时会发生什么,哪些函数成功,哪些返回错误。 -
你在为什么操作系统编程?