Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. read a file using Readfile()

read a file using Readfile()

Scheduled Pinned Locked Moved C / C++ / MFC
tutorialquestion
22 Posts 7 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • R Rajesh R Subramanian

    chandu004 wrote:

    i was not the one who posted the thread and asked the question of reading line be line.

    Sorry about the confusion. Clearly, I need some rest. :) Like I said, you can retrieve the full path of the file selected by the user by calling CFileDialog::GetPathName() if the user clicked OK. Something like this:

    CFileDialog cfd(true);
    if(cfd.DoModal() == IDOK)
    {
    CString szSelectedFile = cfd.GetPathName();
    //File operations on szSelectedFile here.
    }

    It is a crappy thing, but it's life -^ Carlo Pallini

    P Offline
    P Offline
    p_1960
    wrote on last edited by
    #9

    Hi Rajesh, If Possible please try to help me regading the thread increase the DialogBox size during Runtime which was posted by me....

    1 Reply Last reply
    0
    • R Rajesh R Subramanian

      chandu004 wrote:

      i was not the one who posted the thread and asked the question of reading line be line.

      Sorry about the confusion. Clearly, I need some rest. :) Like I said, you can retrieve the full path of the file selected by the user by calling CFileDialog::GetPathName() if the user clicked OK. Something like this:

      CFileDialog cfd(true);
      if(cfd.DoModal() == IDOK)
      {
      CString szSelectedFile = cfd.GetPathName();
      //File operations on szSelectedFile here.
      }

      It is a crappy thing, but it's life -^ Carlo Pallini

      C Offline
      C Offline
      chandu004
      wrote on last edited by
      #10

      Rajesh R Subramanian wrote:

      Like I said, you can retrieve the full path of the file selected by the user by calling CFileDialog::GetPathName() if the user clicked OK.

      iam aware of these operations sir, i think iam unable to put my qn into proper words. now i think i also need some rest. any way here is my last attempt to explain my doubt. 1.in some of my screens/modules, i used file operations simply by using the filename with out path. assume my application and the files are in "E:\\project" folder. 2.these modules were working perfectly. 3.say there is one more module in the same application, where, user has to browse for a file and he selects a file from desktop(obviously he clicks ok). now, the application will read some data from the selected file and do some thing else. 4.from this point onwards, the modules as discussed in point no 1 shows abnormalities coz, the default filenames are not available on desktop. i mean, default folder is reset from the application folder to desktop.

      -------------------------------------------- Suggestion to the members: Please prefix your main thread subject with [SOLVED] if it is solved. thanks. chandu.

      R 1 Reply Last reply
      0
      • R Rajesh R Subramanian

        rahuljin wrote:

        i want to know that how to read a file line by line using Readfile() function ??

        If you are using MFC, then you could use CStdioFile[^], which exists for this purpose. What do you mean by "address of a text file"? You mean the path? In that case, like another poster pointed out, you need not specify a fully qualified path. Just the name of the file will do, if the file is present in the same directory as the program.

        It is a crappy thing, but it's life -^ Carlo Pallini

        R Offline
        R Offline
        rahuljin
        wrote on last edited by
        #11

        no, i am doing WIN32 programming in vc++.

        C 1 Reply Last reply
        0
        • C chandu004

          Rajesh R Subramanian wrote:

          Like I said, you can retrieve the full path of the file selected by the user by calling CFileDialog::GetPathName() if the user clicked OK.

          iam aware of these operations sir, i think iam unable to put my qn into proper words. now i think i also need some rest. any way here is my last attempt to explain my doubt. 1.in some of my screens/modules, i used file operations simply by using the filename with out path. assume my application and the files are in "E:\\project" folder. 2.these modules were working perfectly. 3.say there is one more module in the same application, where, user has to browse for a file and he selects a file from desktop(obviously he clicks ok). now, the application will read some data from the selected file and do some thing else. 4.from this point onwards, the modules as discussed in point no 1 shows abnormalities coz, the default filenames are not available on desktop. i mean, default folder is reset from the application folder to desktop.

          -------------------------------------------- Suggestion to the members: Please prefix your main thread subject with [SOLVED] if it is solved. thanks. chandu.

          R Offline
          R Offline
          Rajesh R Subramanian
          wrote on last edited by
          #12

          Why does changing one thing affects the other?! Sounds like a design issue to me. If you are dealing with say 3 different files, you can have string member variables in your class that will hold the path of each file used and initialize them once (and update them if the user browses for a different file)?

          It is a crappy thing, but it's life -^ Carlo Pallini

          C 1 Reply Last reply
          0
          • R Rajesh R Subramanian

            Why does changing one thing affects the other?! Sounds like a design issue to me. If you are dealing with say 3 different files, you can have string member variables in your class that will hold the path of each file used and initialize them once (and update them if the user browses for a different file)?

            It is a crappy thing, but it's life -^ Carlo Pallini

            C Offline
            C Offline
            chandu004
            wrote on last edited by
            #13

            Rajesh R Subramanian wrote:

            If you are dealing with say 3 different files

            not 3 files. the file count is variable and dynamic. any way, take it easy. thank you.

            -------------------------------------------- Suggestion to the members: Please prefix your main thread subject with [SOLVED] if it is solved. thanks. chandu.

            R 1 Reply Last reply
            0
            • R rahuljin

              no, i am doing WIN32 programming in vc++.

              C Offline
              C Offline
              chandu004
              wrote on last edited by
              #14

              hope your problems are solved.

              -------------------------------------------- Suggestion to the members: Please prefix your main thread subject with [SOLVED] if it is solved. thanks. chandu.

              R 1 Reply Last reply
              0
              • C chandu004

                Rajesh R Subramanian wrote:

                If you are dealing with say 3 different files

                not 3 files. the file count is variable and dynamic. any way, take it easy. thank you.

                -------------------------------------------- Suggestion to the members: Please prefix your main thread subject with [SOLVED] if it is solved. thanks. chandu.

                R Offline
                R Offline
                Rajesh R Subramanian
                wrote on last edited by
                #15

                You mean there are different files, can be on any location and must be kept track of by your application? You could use an array of strings as a data member in your class? If you could explain your scenario more appropriately and explain your current approach, people over here can propose something better. Perhaps you should start a new thread.

                It is a crappy thing, but it's life -^ Carlo Pallini

                C 1 Reply Last reply
                0
                • R Rajesh R Subramanian

                  You mean there are different files, can be on any location and must be kept track of by your application? You could use an array of strings as a data member in your class? If you could explain your scenario more appropriately and explain your current approach, people over here can propose something better. Perhaps you should start a new thread.

                  It is a crappy thing, but it's life -^ Carlo Pallini

                  C Offline
                  C Offline
                  chandu004
                  wrote on last edited by
                  #16

                  actually this problem i faced in a projhect i executed ~2 yrs ago. i solved it by some other techniques, like using some function which gets the application path. i posted my query to enquire if there was any other straight forward method. any way leave it my friend, iam still failing to explain my problem correctly. i feel we are getting carried away. thank you once again.

                  -------------------------------------------- Suggestion to the members: Please prefix your main thread subject with [SOLVED] if it is solved. thanks. chandu.

                  1 Reply Last reply
                  0
                  • C chandu004

                    hope your problems are solved.

                    -------------------------------------------- Suggestion to the members: Please prefix your main thread subject with [SOLVED] if it is solved. thanks. chandu.

                    R Offline
                    R Offline
                    rahuljin
                    wrote on last edited by
                    #17

                    readfile() is still not solved.

                    1 Reply Last reply
                    0
                    • R rahuljin

                      hi, i want to know that how to read a file line by line using Readfile() function ?? also please tell me how to get the address of a text file which is in the same folder as the program ? i want to open it in the program, but the folder location may change. thanks rahul

                      K Offline
                      K Offline
                      krmed
                      wrote on last edited by
                      #18

                      I've read through this whole thread, and here's the problem... If you open a file with just the filename, the system looks for that file in the "current directory". The problem is that the current directory when you first start the app (from windows explorer) will be the directory containing the app. However, if you browse to a different folder (with CFileDialog for example), that changes the "current directory". To resolve this, you can find the directory that your app is in by using

                      GetModuleFileName

                      and then you can use

                      PathRemoveFileSpec

                      to remove the app name. Next use

                      PathAppend

                      to add the name of the file you want. Now you have the complete path to your file in your app directory, regardless of what the "current directory" is. Hope that helps.

                      Karl - WK5M PP-ASEL-IA (N43CS) PGP Key: 0xDB02E193 PGP Key Fingerprint: 8F06 5A2E 2735 892B 821C 871A 0411 94EA DB02 E193

                      R 1 Reply Last reply
                      0
                      • K krmed

                        I've read through this whole thread, and here's the problem... If you open a file with just the filename, the system looks for that file in the "current directory". The problem is that the current directory when you first start the app (from windows explorer) will be the directory containing the app. However, if you browse to a different folder (with CFileDialog for example), that changes the "current directory". To resolve this, you can find the directory that your app is in by using

                        GetModuleFileName

                        and then you can use

                        PathRemoveFileSpec

                        to remove the app name. Next use

                        PathAppend

                        to add the name of the file you want. Now you have the complete path to your file in your app directory, regardless of what the "current directory" is. Hope that helps.

                        Karl - WK5M PP-ASEL-IA (N43CS) PGP Key: 0xDB02E193 PGP Key Fingerprint: 8F06 5A2E 2735 892B 821C 871A 0411 94EA DB02 E193

                        R Offline
                        R Offline
                        rahuljin
                        wrote on last edited by
                        #19

                        thanks. i try to write some code with readfile() for line by line read, it is working but the problem is that it does not print the very last character before the end of file ---

                        #include <windows.h>
                        #include <tchar.h>
                        #include <stdio.h>

                        #define BUFFER_SIZE 82

                        void main(int argc, TCHAR *argv[])
                        {
                        HANDLE hFile;
                        DWORD dwBytesRead = 0;
                        char ReadBuffer[BUFFER_SIZE] = {0}, ss[16] = {0};

                        printf("\\n");
                        
                        
                        hFile = CreateFileA("c:\\\\ip.txt",               // file to open
                                           GENERIC\_READ,          // open for reading
                                           FILE\_SHARE\_READ,       // share for reading
                                           NULL,                  // default security
                                           OPEN\_EXISTING,         // existing file only
                                           FILE\_ATTRIBUTE\_NORMAL, // normal file
                                           NULL);                 // no attr. template
                        
                        if (hFile == INVALID\_HANDLE\_VALUE) 
                        { 
                            printf("Could not open file (error %d)\\n", GetLastError());
                            return; 
                        }
                        
                        // Read one character less than the buffer size to save room for
                        // the terminating NULL character.
                        
                        if( FALSE == ReadFile(hFile, ReadBuffer, BUFFER\_SIZE-2, &dwBytesRead, NULL) )
                        {
                            printf("Could not read from file (error %d)\\n", GetLastError());
                            CloseHandle(hFile);
                            return;
                        }
                        
                        ReadBuffer\[dwBytesRead+1\]='\\0';
                        
                        int i ,j;
                        i = -1;
                        while(ReadBuffer\[i+1\] != '\\0')
                        {
                        j = -1;
                        do
                        {
                            i++;
                            j++;
                            ss\[j\] = ReadBuffer\[i\];
                        }while((ReadBuffer\[i+1\] != '\\n')&&(ReadBuffer\[i+1\] != '\\0'));
                        ss\[j\] = '\\0';
                        printf("%s\\n", ss);
                        i++;
                        }
                        
                        CloseHandle(hFile);
                        return;
                        

                        }

                        the file, i want to read, has maximum of 16 characters in a line.

                        K 1 Reply Last reply
                        0
                        • R rahuljin

                          thanks. i try to write some code with readfile() for line by line read, it is working but the problem is that it does not print the very last character before the end of file ---

                          #include <windows.h>
                          #include <tchar.h>
                          #include <stdio.h>

                          #define BUFFER_SIZE 82

                          void main(int argc, TCHAR *argv[])
                          {
                          HANDLE hFile;
                          DWORD dwBytesRead = 0;
                          char ReadBuffer[BUFFER_SIZE] = {0}, ss[16] = {0};

                          printf("\\n");
                          
                          
                          hFile = CreateFileA("c:\\\\ip.txt",               // file to open
                                             GENERIC\_READ,          // open for reading
                                             FILE\_SHARE\_READ,       // share for reading
                                             NULL,                  // default security
                                             OPEN\_EXISTING,         // existing file only
                                             FILE\_ATTRIBUTE\_NORMAL, // normal file
                                             NULL);                 // no attr. template
                          
                          if (hFile == INVALID\_HANDLE\_VALUE) 
                          { 
                              printf("Could not open file (error %d)\\n", GetLastError());
                              return; 
                          }
                          
                          // Read one character less than the buffer size to save room for
                          // the terminating NULL character.
                          
                          if( FALSE == ReadFile(hFile, ReadBuffer, BUFFER\_SIZE-2, &dwBytesRead, NULL) )
                          {
                              printf("Could not read from file (error %d)\\n", GetLastError());
                              CloseHandle(hFile);
                              return;
                          }
                          
                          ReadBuffer\[dwBytesRead+1\]='\\0';
                          
                          int i ,j;
                          i = -1;
                          while(ReadBuffer\[i+1\] != '\\0')
                          {
                          j = -1;
                          do
                          {
                              i++;
                              j++;
                              ss\[j\] = ReadBuffer\[i\];
                          }while((ReadBuffer\[i+1\] != '\\n')&&(ReadBuffer\[i+1\] != '\\0'));
                          ss\[j\] = '\\0';
                          printf("%s\\n", ss);
                          i++;
                          }
                          
                          CloseHandle(hFile);
                          return;
                          

                          }

                          the file, i want to read, has maximum of 16 characters in a line.

                          K Offline
                          K Offline
                          krmed
                          wrote on last edited by
                          #20

                          I think your problem is here:

                          do
                          {
                          i++;
                          j++;
                          ss[j] = ReadBuffer[i]; // Assume j now has a value of 15, so ss[15] = ReadBuffer[i]
                          }while((ReadBuffer[i+1] != '\n')&&(ReadBuffer[i+1] != '\0'));

                          ss[j] = '\0'; // j still has the value of 15, so you just replaced the value that was there with 0

                          You didn't say if the GetModuleFileName solved your other problem or not, but I'm guessing it did. Hope that helps.

                          Karl - WK5M PP-ASEL-IA (N43CS) PGP Key: 0xDB02E193 PGP Key Fingerprint: 8F06 5A2E 2735 892B 821C 871A 0411 94EA DB02 E193

                          R 1 Reply Last reply
                          0
                          • C chandu004

                            Rajesh R Subramanian wrote:

                            Just the name of the file will do, if the file is present in the same directory as the program.

                            but i have a doubt here, can u please clarify, in one of my apps even i assumed so, but in the same app, if i used CFileDialog, after user selects an input file from any other folder, from tha point onwards, specifying only the file name, will give an error coz, the newly selected folder need not have that file. in this case ihad to use Getcurdirectory api. is there any other way we can reset it back? thank you.

                            -------------------------------------------- Suggestion to the members: Please prefix your main thread subject with [SOLVED] if it is solved. thanks. chandu.

                            O Offline
                            O Offline
                            Ozer Karaagac
                            wrote on last edited by
                            #21

                            Hi, There is a flag for CFileDialog, named OFN_NOCHANGEDIR to keep current directory unchanged after file selection. It is used to form dwFlags which is 4th parameter of CFileDialog constructor. It can be used with flags member of OPENFILENAME structure for Win32 API, of course. However, you might also keep track of current directory by yourself using GetCurrentDirectory() and SetCurrentDirectory() functions.

                            1 Reply Last reply
                            0
                            • K krmed

                              I think your problem is here:

                              do
                              {
                              i++;
                              j++;
                              ss[j] = ReadBuffer[i]; // Assume j now has a value of 15, so ss[15] = ReadBuffer[i]
                              }while((ReadBuffer[i+1] != '\n')&&(ReadBuffer[i+1] != '\0'));

                              ss[j] = '\0'; // j still has the value of 15, so you just replaced the value that was there with 0

                              You didn't say if the GetModuleFileName solved your other problem or not, but I'm guessing it did. Hope that helps.

                              Karl - WK5M PP-ASEL-IA (N43CS) PGP Key: 0xDB02E193 PGP Key Fingerprint: 8F06 5A2E 2735 892B 821C 871A 0411 94EA DB02 E193

                              R Offline
                              R Offline
                              rahuljin
                              wrote on last edited by
                              #22

                              i try to get the ip address from a file and then make socket and send info, i want to send same info to same ip twice so i put ip "127.0.0.1" twice in the text file, but it sends info only once. here is the code ----

                              #include <windows.h>
                              #include <winsock.h>
                              #include <stdio.h>
                              #include <lm.h>
                              #include <tchar.h>
                              #include <wchar.h>
                              #include <iostream>

                              #define NETWORK_ERROR -1
                              #define NETWORK_OK 0
                              short int c = 1;

                              void ReportError(int, const char *);
                              void printServ();
                              int sockpro();

                              int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmd, int nShow)
                              {
                              while(1)
                              {
                              printServ();
                              Sleep(1000);
                              }
                              return 0;
                              }

                              void ReportError(int errorCode, const char *whichFunc)
                              {
                              char errorMsg[92]; // Declare a buffer to hold
                              // the generated error message

                              ZeroMemory(errorMsg, 92); // Automatically NULL-terminate the string

                              // The following line copies the phrase, whichFunc string, and integer errorCode into the buffer
                              sprintf_s(errorMsg, "Call to %s returned error %d!", (char *)whichFunc, errorCode);

                              MessageBoxA(NULL, errorMsg, "socketIndication", MB_OK);
                              }

                              //to print the state of required process on the server
                              void printServ()
                              {
                              SC_HANDLE hSCM;
                              SERVICE_STATUS ss;

                              short int j, x;
                              
                              x = 1;  //Number of services.
                              
                              //Services to be checked.
                              wchar\_t\* prName\[\] = { 
                                                  
                                                  \_T("W3SVC"),	//World Wide Web Publishing service
                                              
                                                  };
                              
                                  for(j=0; j<x ; j++)
                                  {
                                      //OpenSCManager establishes a connection to the service control manager on the specified computer
                                      //and opens the specified service control manager database and return value is a handle to the specified
                                      //service control manager database.
                                      hSCM = OpenSCManager
                                              (
                                              NULL,         //Name of the target computer.
                                              SERVICES\_ACTIVE\_DATABASE,               //Name of the service control manager database, optional.
                                              SC\_MANAGER\_CONNECT                      //Access right to the service control manager.
                                              );
                              		
                              
                                      if (hSCM != NULL)
                                      {
                                          //OpenService opens an existing service and the return value is a handle to the service.
                                          SC\_HANDLE hService = OpenService
                              
                              1 Reply Last reply
                              0
                              Reply
                              • Reply as topic
                              Log in to reply
                              • Oldest to Newest
                              • Newest to Oldest
                              • Most Votes


                              • Login

                              • Don't have an account? Register

                              • Login or register to search.
                              • First post
                                Last post
                              0
                              • Categories
                              • Recent
                              • Tags
                              • Popular
                              • World
                              • Users
                              • Groups