File handling operations Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

writing to a text file

A

1) before it is accessed/opened, it has to be given a file handle (a reference assigned to the file so the program can use it):
myFile = openWrite(“Sample.txt”)

2) when a file is opened in write mode, a new file is created with the name if it doesn’t already exist
3) if a file already exists, it is overwritten and the existing data is lost most languages have an ‘OpenAppend’ command to prevent this

4) once a file has been read from/written to, it must be closed:
myFile.close()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

writing directly

A

a user can open a file and write data directly to it from the keyboard

myFile = openWrite(“Sample.txt”)
myFile.writeLine(“example”)
myFile.close()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

writing indirectly

A

a program can be coded to save data stored in variables to a text file

e.g.
scoreFile.writeLine(array[index])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

reading data from a file

A

a program can open a text file to read data

data stored in text files can be loaded into the variables of a program

if the number to read to is not known, the endOfFile() function can be used

e.g.
myFile = openRead(“Sample.txt”)

scoreFile = openRead("highScores.txt")
for index = 0 to 4
    highScores[index] = scoreFile.readLine()
next index
scoreFile.close()

while NOT scoreFile.endOfFile()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

A student has coded a program that allows users to answer a multiple choice test. The user’s name is stored in the ‘userName’ variable and their score in the ‘testScore’ variable.

Insert the code that would allow the score to be saved in a text file with the users name in the filename. [4]

A

userFile = openWrite(username + “.txt”)
userFile.writeLine(testScore)
userFile.close()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

When using a program, a user is asked to create a username. Write a program that will ask a user to enter a username and check to see if it has already been used. Usernames are stored in a text file named ‘users’.

If it has already been used, the routine should inform the user and ask them to enter a new one. [8]

A
userName = input("Please enter a username.")
userFile = openRead("users.txt")
used = false
while NOT userFile.endOfFile()
    storedName = userFile.readLine()
    if storedName == userName then
        used = true
    endif
endwhile
userFile.close()

if used == true then
print(“Sorry this username has already been taken.
Please enter a new username.”)
endif

How well did you know this?
1
Not at all
2
3
4
5
Perfectly