Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Visual Basic: Copying a File

  1. Nov 29, 2015 #1

    phion

    User Avatar
    Gold Member

    Hi,

    I'm having trouble figuring out how to copy the contents of a file over to another file, and removing an item of the content of the list I'm copying in the process. The idea is that I need to remove an item from a list by copying everything that is in file one over to file two that is not the item I need to remove, deleting the original file, and the renaming the second file to the original. I can't seem to get it to work.

    Here's the function that main calls.

    Code (Text):

    Function removePlayer(playerList() As String, numPlayers As Integer) As Integer
            Dim updatedPlayers As Integer
            Dim player As String
            Dim fileName As String = "playerList.txt"
            Dim tempFileName As String = "tempPlayerList.txt"
            Dim inFile As New StreamReader(fileName)
            Dim outFile As New StreamWriter(tempFileName)

            Console.WriteLine("Which player would you like to remove?")

            player = Console.ReadLine()

            While Not inFile.EndOfStream

                For i = 0 To numPlayers - 1

                    playerList(i) = inFile.ReadLine()

                    If playerList(i) <> player Then

                        outFile.WriteLine(playerList(i))

                    End If

                Next

            End While

            inFile.Close()
            outFile.Close()

            File.Delete("playerList.txt")

            My.Computer.FileSystem.RenameFile("C:\Users\John\Desktop\addPLayerList\bin\Debug\tempPlayerList.txt", "playerList.txt")

            File.Create("C:\Users\John\Desktop\addPLayerList\bin\Debug\tempPlayerList.txt")

            updatedPlayers = numPlayers - 1

            Return updatedPlayers
        End Function

     
     
  2. jcsd
  3. Nov 29, 2015 #2

    phinds

    User Avatar
    Gold Member
    2016 Award

    "Doesn't work" is a useless characterization of what you are experiencing. OK, it doesn't do what you want. Fine. What DOES it do? What are the symptoms of the error?
     
  4. Nov 29, 2015 #3

    Andrew Mason

    User Avatar
    Science Advisor
    Homework Helper

    The problem may be with the use of <> for strings.

    Rather than use "If playerList(i) <> player Then" you might use:

    x = Instr(playerList(i), player)
    if x = 0 then
    outFile.WriteLine(playerList(i))
    endif

    You might also want to ensure that all strings are put to the same case (ucs or lcs) when comparing.

    AM
     
  5. Nov 29, 2015 #4

    phion

    User Avatar
    Gold Member

    It doesn't effectively delete an item from the list, but what it does do is copy the whole list to a temporary file, delete the original, and rename the temporary file to the original name. I need it to leave out the item to be deleted when it copies the list over to the new file.
     
  6. Nov 29, 2015 #5

    phinds

    User Avatar
    Gold Member
    2016 Award

    Then clearly, your test "playerList(i) <> player" isn't doing what you want. Are you sure you are typing in EXACTLY what is in the line you want to get rid of? Case matters.
     
  7. Nov 29, 2015 #6

    phion

    User Avatar
    Gold Member

    Now what it's doing is deleting the last item in the list regardless of what name I specify to be deleted. Strange.
     
  8. Nov 29, 2015 #7

    phinds

    User Avatar
    Gold Member
    2016 Award

    Are you saying that it is now deleting the one you want AND the last one or just the last one? PLEASE be exact when you are describing these conditions. Trying to guess what you mean is annoying.
     
  9. Nov 29, 2015 #8

    phion

    User Avatar
    Gold Member

    It's only deleting the last item in the list, no matter what item I want deleted.
     
  10. Nov 29, 2015 #9

    phinds

    User Avatar
    Gold Member
    2016 Award

    Sounds like you are passing a number that tells it to read one less than you want it to read plus whatever is causing it to not delete the one you type in.
     
  11. Nov 29, 2015 #10

    Andrew Mason

    User Avatar
    Science Advisor
    Homework Helper

    If you could provide us with a sample of playerList.txt we might have a better idea.

    It is deleting the last line because you are starting at 0 instead of 1. Try starting at 1.

    To figure out why it is treating as true: playerList(i) <> player when playerList(i) = player you just have to display these variables and see what it is doing. Just insert a msgbox line eg:

    For i = 1 To numPlayers

    playerList(i) = inFile.ReadLine()
    msgbox("playerList(" & i ") = " & playerList(i) & " ; player = " & player)

    If playerList(i) <> player Then
    msgbox("Printing playerList(" & i ") = " playerList(i))
    outFile.WriteLine(playerList(i))

    End If​

    Next​


    Also: it is not clear how you determine numPlayers. Why not just let the for loop continue until you reach the end of the infile?

    AM
     
    Last edited: Nov 29, 2015
  12. Nov 30, 2015 #11

    phion

    User Avatar
    Gold Member

    playerList.txt displays a simple list of names that the user has input.

    John
    Tim
    Sara
    Alex

    Then the program will ask, if the user chooses, which name they would like to remove from the list. If I choose, say, John to be removed the list becomes

    John
    Tim
    Sara

    When it should be

    Tim
    Sara
    Alex
     
  13. Nov 30, 2015 #12

    phion

    User Avatar
    Gold Member

    numPlayers is assigned in a different function where the user adds the players to the list.

    I tried just using the for loop and what happens is that every name on the list gets replaced with the name I want to remove.
     
  14. Nov 30, 2015 #13

    Andrew Mason

    User Avatar
    Science Advisor
    Homework Helper

    In addition to starting at i=1, You should make sure the comparison is case indifferent. You should also make sure there are no leading or trailing spaces:

    dim uplayer as string
    dim uplayerlist as string
    ...
    uplayer = UCase(player)
    uplayer=Trim(uplayer)

    For i = 1 To numPlayers

    playerList(i) = inFile.ReadLine()
    uplayerlist= UCase(playerList(i))
    uplayerlist = Trim(uplayerlist)

    If uplayerlist <> uplayer Then
    outFile.WriteLine(playerList(i))

    End If

    Next​

    Again, you should make sure that the number of lines in the input file does not exceed numPlayers. To avoid a problem with that you can just keep reading lines until you reach the end of file.

    AM
     
    Last edited: Nov 30, 2015
  15. Nov 30, 2015 #14

    phion

    User Avatar
    Gold Member

    It's still not doing what I need it to. Here's what I have, it's a small part of a bigger program.

    Code (Text):

    Imports System.IO

    Module Module1

        Sub Main()
            Const SIZE As Integer = 50
            Dim playerList(SIZE), tempPlayerList(SIZE) As String
            Dim numPlayers As Integer

            numPlayers = loadList(playerList)

            numPlayers = addPlayers(playerList, numPlayers)

            displayList(playerList, numPlayers)

            numPlayers = removePlayer(playerList, numPlayers)

            displayList(playerList, numPlayers)

            saveList(playerList, numPlayers)

            Console.WriteLine("List saved successfully!")

        End Sub

        Function loadList(playerList() As String) As Integer
            Dim numPlayers As Integer
            Dim fileName As String = "playerList.txt"

            numPlayers = 0

            If File.Exists(fileName) Then

                Dim inFile As New StreamReader(fileName)

                While Not inFile.EndOfStream

                    playerList(numPlayers) = inFile.ReadLine()

                    numPlayers += 1

                End While

                inFile.Close()

            Else
                Console.WriteLine("Could Not Open " & fileName)
            End If

            Return numPlayers
        End Function

        Function addPlayers(playerList() As String, numPlayers As Integer) As Integer
            Dim newPlayer As String

            Console.Write("Enter player name ('exit' to quit): ")

            newPlayer = Console.ReadLine()

            While newPlayer <> "exit"

                playerList(numPlayers) = newPlayer

                numPlayers += 1

                Console.Write("Enter player name ('exit' to quit): ")

                newPlayer = Console.ReadLine()

            End While

            Return numPlayers

        End Function

        Sub displayList(playerList() As String, numPlayers As Integer)
            Dim i As Integer

            For i = 0 To numPlayers - 1

                Console.WriteLine("Player " & i + 1 & ": " & playerList(i))

            Next

        End Sub

        Function removePlayer(playerList() As String, numPlayers As Integer) As Integer
            Dim updatedPlayers As Integer
            Dim player As String
            Dim fileName As String = "playerList.txt"
            Dim tempFileName As String = "tempPlayerList.txt"
            Dim inFile As New StreamReader(fileName)
            Dim outFile As New StreamWriter(tempFileName)

            Console.WriteLine("Which player would you like to remove?")

            player = Console.ReadLine()

            For i = 1 To numPlayers

                playerList(i) = inFile.ReadLine()

                If player <> playerList(i) Then

                    outFile.WriteLine(playerList(i))

                End If

            Next

            inFile.Close()
            outFile.Close()

            File.Delete("playerList.txt")

            My.Computer.FileSystem.RenameFile("C:\Users\John\Desktop\addPLayerList\bin\Debug\tempPlayerList.txt", "playerList.txt")

            File.Create("C:\Users\John\Desktop\addPLayerList\bin\Debug\tempPlayerList.txt")

            updatedPlayers = numPlayers - 1

            Return updatedPlayers
        End Function

        Sub saveList(playerList() As String, numPlayers As Integer)
            Dim fileName As String = "playerList.txt"
            Dim outFile As New StreamWriter(fileName)

            For i = 0 To numPlayers - 1

                outFile.WriteLine(playerList(i))

            Next

            outFile.Close()
        End Sub

    End Module

     
    This code works just as I need it to, except when I try to remove a player. I tried taking out the while loop and only using a for loop, but it still just replaces every name with the name I want to remove. I'm careful to use the right cases so I'm not too worried about that part just yet.
     
  16. Nov 30, 2015 #15

    mfb

    User Avatar
    2016 Award

    Staff: Mentor

    I don't get the logic:
    loadList reads in a file and puts the player list into an array "playerList".
    addPlayers modifies this array: it adds an element.
    displayList prints out the array.
    saveList saves the array. All consistent so far.
    removePlayer does not care about the existing array at all, it reads the file again and processes it.

    Your array seems to begin at zero (see saveList and displayList), so you should start at zero in your loop.

    This code (your last post) replaces entries with the input? Then something odd happens with outFile.WriteLine(playerList(i)). Did you check what is stored at playerList(i) at that point?
    What happens if you use a player name (to be removed) not present in the list?
    Does saveList work properly?
     
  17. Nov 30, 2015 #16

    phion

    User Avatar
    Gold Member

    Save list works fine. Using a name not on the list actually causes every name except the first to be removed. This is weird.

    I set the starting index back to 0 and it's just deleting everything after the first name again. I simply don't understand.
     
  18. Nov 30, 2015 #17

    mfb

    User Avatar
    2016 Award

    Staff: Mentor

    Okay, your outFile.WriteLine() does something weird.
    What happens if you replace it by outFile.WriteLine("Test")?
     
  19. Nov 30, 2015 #18

    Andrew Mason

    User Avatar
    Science Advisor
    Homework Helper

    I thought numPlayers was a fixed number ie. that does not change. What you appear to be trying to do here is use it as an index.

    I am not familiar with the numPlayers += 1 statement. Is it supposed to increment by 1 every iteration, starting at 1? If it does not do that the index will be wrong.

    AM
     
  20. Dec 1, 2015 #19

    Samy_A

    User Avatar
    Science Advisor
    Homework Helper

    I have to agree with @mfb , the logic of the program is strange.
    What your code apparently does:
    1. You load a file into the array.
    2. You let users add names to that array.
    3. You display the array.
    4. In removePlayer, you let the user enter a name and then you reload the file (hereby discarding the names added in step 2), fill the array with all the names in the file (including the name the user wants to remove), and save the file with all the names except the one your user chose to remove. However, you loop from 0 to numPlayers-1, where numPlayers is the number of names in the array before you called removePlayer, not necessarily the number of names in the file.
      Then you subtract 1 from numPlayers, irrespective of whether the name to be removed was present in the file or not.
      If I read it correctly, after executing removePlayer, numPlayers wll be one less than the number of names in the array before you called removePlayer.
    5. You display the array.
    6. You save the array.
    These apparent inconsistencies don't explain the results that you get, but certainly don't make debugging this program easier.
    It would also help if you could tell us where you see the weird results: is it when you display the array in step 5, or is when you look at the file?
     
    Last edited: Dec 1, 2015
  21. Dec 1, 2015 #20

    phion

    User Avatar
    Gold Member

    Since the index of the first element in an array is zero, the for loop starts at zero because that corresponds to the first name in the array.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Visual Basic: Copying a File
  1. Fortran / Visual Basic ? (Replies: 13)

Loading...