fortran - 如何删除 Fortran 文件中的特定行?
问题描述
我必须制作一个编辑待办事项列表的应用程序(文件 to_do.txt)。我可以阅读它,也可以添加新任务,但我无法删除文件的特定行而不破坏所有内容。我该怎么做?这是我的代码
program compito4
implicit none
! Declaring the variables
integer :: unit, stat, counter, i
character (len = 1) action
character (len = 200) line, new_task
! Open the program
open(newunit = unit, file = 'to_do.txt', status = 'OLD', position = 'APPEND')
do
print *, 'What would you like to do? (a)dd, (d)elete, (l)ist, (q)uit'
read (*,*) action
if (action == 'a') then
print *, 'Insert the new task'
read (*, '(A)') new_task
write (unit, '(A)') '\n' // new_task ! // is the string concatenation operator
print *, 'New task successfully added'
else if (action == 'd') then
print *, 'Insert the number of the task to be removed'
read (*,*) i
print *, i
counter = 0
rewind unit
do
read(unit, '(A)', iostat = stat) line
if (stat .ne. 0) then
backspace unit
exit
else if (i == counter) then
print *, 'You are in the right spot'
print *, counter
backspace unit
write (unit, '(2A)') trim(line), ('->Task done')
end if
counter = counter + 1
end do
else if (action == 'l') then
rewind unit
counter = 0
do
read(unit, '(A)', iostat = stat) line
if (stat .ne. 0) then ! It handles the end of file!
backspace unit
exit
end if
print *, counter,') ', line
counter = counter + 1
end do
else if (action == 'q') then
print *, 'Closing the program'
exit
else
print *, 'Invalid choice'
end if
end do
close(unit)
end program compito4