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 Offline
    R Offline
    rahuljin
    wrote on last edited by
    #1

    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

    C S R K 4 Replies 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

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

      rahuljin wrote:

      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

      in most of the cases, though the folder location changes, the files available inthe folder same as the exe can be accessed direcly by its name. i mean no path need to be specified.

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

      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

        S Offline
        S Offline
        Sarath C
        wrote on last edited by
        #3

        Opening a File for Reading or Writing[^] The folders in the working directory is always accessible by it's name. Only few APIs insist to give the entire path of the file name. In such cases, You can call GetCurrentDirectory API to get the current directory path and append the file name with _T( "\\" ) (C++ notification for '\') using any of the string concatenating function.

        -Sarath. "Great hopes make everything great possible" - Benjamin Franklin

        My blog - Sharing My Thoughts

        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

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

          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

          C R 2 Replies 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

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

            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.

            R O 2 Replies 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.

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

              CFileDialog?! So, you're using MFC. Then you must use CStdioFile class to read file (you said line by line) instead of ReadFile() and that will make things simpler for you.

              chandu004 wrote:

              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.

              CFileDialog::GetPathName()[^] returns the full path of the file selected by the user (of course, if clicked OK).

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

              C 1 Reply Last reply
              0
              • R Rajesh R Subramanian

                CFileDialog?! So, you're using MFC. Then you must use CStdioFile class to read file (you said line by line) instead of ReadFile() and that will make things simpler for you.

                chandu004 wrote:

                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.

                CFileDialog::GetPathName()[^] returns the full path of the file selected by the user (of course, if clicked OK).

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

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

                Rajesh R Subramanian wrote:

                CFileDialog?! So, you're using MFC. Then you must use CStdioFile class to read file (you said line by line) instead of ReadFile() and that will make things simpler for you

                no no, i was not the one who posted the thread and asked the question of reading line be line. my question is, normally, without specifying the path, the files in the curdir can be accessed by default. but in the same app, if we had used CFileDialog::DoModal(); after that, the above condition would not be applicable. i wanted to understand from you, if there is any way to overcome this.

                -------------------------------------------- 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:

                  CFileDialog?! So, you're using MFC. Then you must use CStdioFile class to read file (you said line by line) instead of ReadFile() and that will make things simpler for you

                  no no, i was not the one who posted the thread and asked the question of reading line be line. my question is, normally, without specifying the path, the files in the curdir can be accessed by default. but in the same app, if we had used CFileDialog::DoModal(); after that, the above condition would not be applicable. i wanted to understand from you, if there is any way to overcome this.

                  -------------------------------------------- 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
                  #8

                  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 C 2 Replies 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

                    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
                                          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