File into Listbox

This is a discussion on File into Listbox within the Windows Programming forums, part of the Platform Specific Boards category; Hey, I have a text file like this: Code: 566.33 988.33 122.33 112.33 333.33 I need to put this file ...

  1. #1
    Registered User (TNT)'s Avatar
    Join Date
    Aug 2001
    Location
    UK
    Posts
    339

    File into Listbox

    Hey,

    I have a text file like this:

    Code:
    566.33
    988.33
    122.33
    112.33
    333.33

    I need to put this file line by line into a ListBox control.

    I know how to add the string to the listbox, if someone could just
    give me some code to put in a loop that will read the file line by line into a string that i can then send to the listbox.

    Thanks for any help.
    TNT
    TNT
    You Can Stop Me, But You Cant Stop Us All

  2. #2
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,789
    Code:
    #include <string>
    using std::string;
    #include <cstring>
    #include <cstdlib>
    #include <windows.h>
    
    #define MAX_TOKENS 5
    
    int main()
    {
    HANDLE hFile;
    DWORD dwSize,dwReadSize;
    char *lpBuffer = 0,
     *strPtr, //A pointer which is the return of strtok()
     *strP1[MAX_TOKENS];//Buffers as array of 2 pointers
    int x = 0;
    string sResult;
    
    hFile = CreateFile("text.txt",GENERIC_READ,0, NULL,OPEN_EXISTING,
     FILE_ATTRIBUTE_NORMAL,
     NULL); //Open File for reading
    
    if(!hFile){
    MessageBox(0,"Error with file","Error",MB_OK);
    exit(0);
    }
    
    dwSize = GetFileSize(hFile,NULL);//Get the size of the file
    lpBuffer = (char*)GlobalAlloc(0,dwSize+1); //Create a read in buffer
    
    if(!lpBuffer){
    MessageBox(0,"Error with memory allocation","Error",MB_OK);
                    CloseHandle(hFile);
    exit(0);
    }
    
    ReadFile(hFile,lpBuffer,dwSize + 1,&dwReadSize,NULL);//Suck up file contents to buffer
    
    lpBuffer[(int)dwSize] = '\0';//NULL terminate
    
    char strcopy[(int)dwSize +1];//A copy to stop original info being chewed up
    
    strcpy(strcopy,lpBuffer); //make copy to tokenize
    
    strPtr = strtok(strcopy,"\n");//Set Strtok to beginning of strcopy. Use '\n' for delimiter
    
    while(strPtr && x < MAX_TOKENS){//while token is not NULL and less than total tokens
    strP1[x] = new char[100]; //Create space dynamically
    strcpy(strP1[x],strPtr);//Copy token into buffer array
    strPtr = strtok(NULL,"\n");//Force strtok up the string
    x++;
    }
    for(int y = 0;y<x;y++){
    sResult += "Found token - ";
    sResult += strP1[y];
    sResult += "\n";
    delete strP1[y]; //Clean up after myself
    
    //SetDlgText().......
    }
    MessageBox(0,sResult.c_str(),"Results",MB_OK);
    GlobalFree(lpBuffer);//free memory
    CloseHandle(hFile);//close file
    return 0;
    }
    This fits in with what you were asking a while ago on strtok().

    I reused the code I gave ,but read from a file and used '\n' as the token delimiter instead of space....

    The code sucks up the contents of a file called "text.txt", makes a copy and then tokenises it.

    I used some windows funcs CreateFile() & GlobalAlloc() cuz I am trying to get used to using them . Also I used the string class cuz its so easy to use.

  3. #3
    Registered User (TNT)'s Avatar
    Join Date
    Aug 2001
    Location
    UK
    Posts
    339
    Thanks Fordy thats what i wanted thers one problem though, i dont know how many tokens it will need to be in. This is because the program adds data to the file. So there wont be a set amount of lines to add to the list box. This means i cant define max tokens as 5, i was just using 5 as an example. Do you know how i can find out how many lines are in the file to start with.

    Thanks alot
    TNT
    TNT
    You Can Stop Me, But You Cant Stop Us All

  4. #4
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,789
    Yeah....

    The way I would do it is with a variable sized container of some sort....

    When I get home I'll work something out for you....

  5. #5
    It's full of stars adrianxw's Avatar
    Join Date
    Aug 2001
    Posts
    4,831
    Do all lines in the file have the same length, (i.e. 6 characters)? If so you can divide the file size by the line length, (remembering the extra characters terminating the lines - load the file into a hex aditor), to find out how many lines.

    Easier I would have thought, is to read the file one line at a time until you reach EOF.
    Wave upon wave of demented avengers march cheerfully out of obscurity unto the dream.

  6. #6
    It's full of stars adrianxw's Avatar
    Join Date
    Aug 2001
    Posts
    4,831
    Oooh, concurrence... we can't go on meeting like this Fordy!
    Wave upon wave of demented avengers march cheerfully out of obscurity unto the dream.

  7. #7
    Registered User
    Join Date
    Feb 2002
    Posts
    14

    Exclamation What about ANSI C?

    #include <stdio.h>
    Code:
      FILE *TextFile;
      char sFileName[] = "file1.txt";
      char sBuff[200];
    
      /* Try to open */
      if ( (TextFile = fopen(sFileName,"r")) == NULL)
      {
        /* File cannot be opened */
        //return -1;
      }
     
      while ( !(feof(TextFile) || ferror(TextFile)) )
      {
        /* Read a line into sBuff */
        fgets(sBuff, sizeof(sBuff), TextFile);
       
        /* Place your code here */
    
      }
     
      /* Close file */
      fclose(TextFile);
    Dharius

  8. #8
    Registered User (TNT)'s Avatar
    Join Date
    Aug 2001
    Location
    UK
    Posts
    339
    Ok thanks people, the file lines are not the same length... I will give Dharius code a try though it looks promising. I will let you know if i have problems,

    Thanks
    TNT
    TNT
    You Can Stop Me, But You Cant Stop Us All

  9. #9
    Registered User (TNT)'s Avatar
    Join Date
    Aug 2001
    Location
    UK
    Posts
    339
    Hey i got the code to work, and the file is added line by line into the list box. I havnt used listboxes for a while and am having a few problems.

    How do i erase all the strings from the listbox. Also how do i get the curret selected string into a buffer.

    Thanks for the help
    TNT
    TNT
    You Can Stop Me, But You Cant Stop Us All

  10. #10
    Registered User johnnie2's Avatar
    Join Date
    Aug 2001
    Posts
    186
    Use the LB_RESETCONTENT message to erase everything.

    Get the string form of the current selection first by making sure something is selected, getting the item's index (LB_GETCURSEL), and using that value with LB_GETTEXT.
    "Optimal decisions, once made, do not need to be changed." - Robert Sedgewick, Algorithms in C

  11. #11
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,789
    I use SetWindowText() on the edit box to clear it.....

    Always worked.......

    Anyway.......

    I tried what you wanted by simply sucking up the data and using SetWindowText() again to load it into the edit control......it didnt work, cuz each line end needs '\r\n' instead of just '\r'....so I went back to the tokeniser and did this

    Code:
    void File2Display(HWND hEdit,char* szFile){
    
    HANDLE hFile;
    DWORD dwSize,dwReadSize;
    char *lpBuffer = 0,
    		*strPtr; //A pointer which is the return of strtok()
    int x = 0;
    string data("");
    
    hFile = CreateFile(szFile,GENERIC_READ,0, NULL,OPEN_EXISTING,
    		 FILE_ATTRIBUTE_NORMAL,
    		 NULL); //Open File for reading
    
    if(hFile == INVALID_HANDLE_VALUE){
    		MessageBox(0,"Error with file","Error",MB_OK);
    		return;
    }
    
    dwSize = GetFileSize(hFile,NULL);//Get the size of the file
    lpBuffer = (char*)GlobalAlloc(0,dwSize+1); //Create a read in buffer
    
    if(!lpBuffer){
    MessageBox(0,"Error with memory allocation","Error",MB_OK);
            CloseHandle(hFile);
            return;	
    }
    
    ReadFile(hFile,lpBuffer,dwSize + 1,&dwReadSize,NULL);//Suck up file contents to buffer
    lpBuffer[(int)dwSize] = '\0';
    
    strPtr = strtok(lpBuffer,"\n");//Set Strtok to beginning of strcopy. Use '\n' for delimiter
    
    while(strPtr){//while token is not NULL and less than total tokens
    data += strPtr;//Copy token into buffer array
    data += "\r\n";
    strPtr = strtok(NULL,"\n");//Force strtok up the string
    x++;
    }
    
    SetWindowText(hEdit,data.c_str());
    GlobalFree(lpBuffer);//free memory
    CloseHandle(hFile);//close file
    }
    If you use this as a general function, it should work....well I tried it and it worked fine....

    Just send the function the HWND from the edit control, and a string saying the name of the file.......

  12. #12
    Just one more wrong move. -KEN-'s Avatar
    Join Date
    Aug 2001
    Posts
    3,230
    >>I use SetWindowText() on the edit box to clear it.....

    Right, which would be absolutely perfect if he were working with edit boxes, wouldn't it?


    The easiest way to put the file in the listbox is with ANSI C. Trust me. I've tried both ways.

    As for getting the selection...::digs up old code::

    Code:
    int index; //Index for the currently selected line.
    char Buffer[MAX]; //Buffer to hold the data
    ...		
     if(LOWORD(wParam) == ID_LIST && HIWORD(wParam) == LBN_DBLCLK){
         index = SendMessage(hwndList, LB_GETCURSEL, 0, 0);
         SendMessage(hwndList, LB_GETTEXT, index, (LPARAM)Buffer);
    }

  13. #13
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,789
    >>I use SetWindowText() on the edit box to clear it.....

    Right, which would be absolutely perfect if he were working with edit boxes, wouldn't it?
    Gah.......Damn......now I have read it properly, I can see that....

    Doh....I need glasses....

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A development process
    By Noir in forum C Programming
    Replies: 37
    Last Post: 07-10-2011, 10:39 PM
  2. Making a LIB file from a DEF file for a DLL
    By JMPACS in forum C++ Programming
    Replies: 0
    Last Post: 08-02-2003, 08:19 PM
  3. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM
  4. Need a suggestion on a school project..
    By Screwz Luse in forum C Programming
    Replies: 5
    Last Post: 11-27-2001, 01:58 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21