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
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Manipulate text file

Manipulate text file

Scheduled Pinned Locked Moved C / C++ / MFC
question
11 Posts 5 Posters 1 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.
  • M Member_538383

    Hi I need to open a text file, edit it, then save it with these modifications, how can I ?

    T Offline
    T Offline
    toxcct
    wrote on last edited by
    #2

    fopen("C:\\folder\\file.txt", "a+");


    TOXCCT >>> GEII power

    1 Reply Last reply
    0
    • M Member_538383

      Hi I need to open a text file, edit it, then save it with these modifications, how can I ?

      V Offline
      V Offline
      V 0
      wrote on last edited by
      #3

      FILE *handletofile; handletofile = fopen("pathtofile", "a+"); //open the file fscanf(handletofile, "%s", string); //for reading fprintf(handletofile, "%s", string); //for writing fclose(handletofile); //close file (do not forget!) fread and fwrite for binary files. use fseek to set your pointer to a specific place in the file. do not open in beginning of exec. and close at end. open/close more often to flush the text and to have something in case your program crashes. Good Luck. "If I don't see you in this world, I'll see you in the next one... and don't be late." ~ Jimi Hendrix

      C 1 Reply Last reply
      0
      • V V 0

        FILE *handletofile; handletofile = fopen("pathtofile", "a+"); //open the file fscanf(handletofile, "%s", string); //for reading fprintf(handletofile, "%s", string); //for writing fclose(handletofile); //close file (do not forget!) fread and fwrite for binary files. use fseek to set your pointer to a specific place in the file. do not open in beginning of exec. and close at end. open/close more often to flush the text and to have something in case your program crashes. Good Luck. "If I don't see you in this world, I'll see you in the next one... and don't be late." ~ Jimi Hendrix

        C Offline
        C Offline
        chauteen
        wrote on last edited by
        #4

        hi, Can you say something more about fseek please? how to use fseek to go to a certain line of a file. For examlpe, I need to overwrite the thrid line of the file. But fseek and fgetpos simply moving the file pointer in the same line, not be able to next line. Thankx. chauteen

        V 1 Reply Last reply
        0
        • C chauteen

          hi, Can you say something more about fseek please? how to use fseek to go to a certain line of a file. For examlpe, I need to overwrite the thrid line of the file. But fseek and fgetpos simply moving the file pointer in the same line, not be able to next line. Thankx. chauteen

          V Offline
          V Offline
          V 0
          wrote on last edited by
          #5

          doesn't fscanf read the "\t", "\n" characters? if so. read the entire file in CString and handle the CString. (you can always google, Codeguru, codeproject on tutorials and examples.) info on fseek from MSDN: Run-Time Library Reference fseekSee Also Stream I/O Routines | ftell | _lseek | rewind | Run-Time Routines and .NET Framework Equivalents Requirements Function Required header Compatibility fseek ANSI, Win 98, Win Me, Win NT, Win 2000, Win XP For additional compatibility information, see Compatibility in the Introduction. Libraries All versions of the C run-time libraries. Moves the file pointer to a specified location. int fseek( FILE *stream, long offset, int origin ); Parameters stream Pointer to FILE structure. offset Number of bytes from origin. origin Initial position. Return Value If successful, fseek returns 0. Otherwise, it returns a nonzero value. On devices incapable of seeking, the return value is undefined. Remarks The fseek function moves the file pointer (if any) associated with stream to a new location that is offset bytes from origin. The next operation on the stream takes place at the new location. On a stream open for update, the next operation can be either a read or a write. The argument origin must be one of the following constants, defined in STDIO.H: SEEK_CUR Current position of file pointer. SEEK_END End of file. SEEK_SET Beginning of file. You can use fseek to reposition the pointer anywhere in a file. The pointer can also be positioned beyond the end of the file. fseek clears the end-of-file indicator and negates the effect of any prior ungetc calls against stream. When a file is opened for appending data, the current file position is determined by the last I/O operation, not by where the next write would occur. If no I/O operation has yet occurred on a file opened for appending, the file position is the start of the file. For streams opened in text mode, fseek has limited use, because carriage return–linefeed translations can cause fseek to produce unexpected results. The only fseek operations guaranteed to work on streams opened in text mode are: Seeking with an offset of 0 relative to any of the origin values. Seeking from the beginning of the file with an offset value returned from a call to ftell. Also in text mode, CTRL+Z is interpreted as an end-of-file character on input. In files opened for reading/writing, fopen and all related routines check for a CTRL+Z at t

          C 1 Reply Last reply
          0
          • V V 0

            doesn't fscanf read the "\t", "\n" characters? if so. read the entire file in CString and handle the CString. (you can always google, Codeguru, codeproject on tutorials and examples.) info on fseek from MSDN: Run-Time Library Reference fseekSee Also Stream I/O Routines | ftell | _lseek | rewind | Run-Time Routines and .NET Framework Equivalents Requirements Function Required header Compatibility fseek ANSI, Win 98, Win Me, Win NT, Win 2000, Win XP For additional compatibility information, see Compatibility in the Introduction. Libraries All versions of the C run-time libraries. Moves the file pointer to a specified location. int fseek( FILE *stream, long offset, int origin ); Parameters stream Pointer to FILE structure. offset Number of bytes from origin. origin Initial position. Return Value If successful, fseek returns 0. Otherwise, it returns a nonzero value. On devices incapable of seeking, the return value is undefined. Remarks The fseek function moves the file pointer (if any) associated with stream to a new location that is offset bytes from origin. The next operation on the stream takes place at the new location. On a stream open for update, the next operation can be either a read or a write. The argument origin must be one of the following constants, defined in STDIO.H: SEEK_CUR Current position of file pointer. SEEK_END End of file. SEEK_SET Beginning of file. You can use fseek to reposition the pointer anywhere in a file. The pointer can also be positioned beyond the end of the file. fseek clears the end-of-file indicator and negates the effect of any prior ungetc calls against stream. When a file is opened for appending data, the current file position is determined by the last I/O operation, not by where the next write would occur. If no I/O operation has yet occurred on a file opened for appending, the file position is the start of the file. For streams opened in text mode, fseek has limited use, because carriage return–linefeed translations can cause fseek to produce unexpected results. The only fseek operations guaranteed to work on streams opened in text mode are: Seeking with an offset of 0 relative to any of the origin values. Seeking from the beginning of the file with an offset value returned from a call to ftell. Also in text mode, CTRL+Z is interpreted as an end-of-file character on input. In files opened for reading/writing, fopen and all related routines check for a CTRL+Z at t

            C Offline
            C Offline
            chauteen
            wrote on last edited by
            #6

            Thanks for your reply first. For I am trying your way, to read the entire file and then write the whole data back.(the work I want to do is store 8 spin vlaue to a file, and update when the user click and change spin value.) but I use a brute force way, for I don't know how to read data in CString:confused: I declare an BYTE array, called buffer[8], and in the dialog's init, I read in the file fread( buffer, sizeof( BYTE ), 8, filespin ); and in the spin message, I add fseek(filespin, 0, SEEK_SET); fprintf( filespin, "%s", buffer ); I've also tried fwrite fwrite( buffer, sizeof( BYTE ), 8, filespin ); both failed the output file will contain some strange code, like slash , camma or something. I try to show the readin buffer text on a editbox, and it already contain a unexpected slash and the end.:confused: It seems the read in have something wrong already, not to mention write data back. Can you suggest me some smart or "correct" way to do? Thank you very much. chauteen

            V 1 Reply Last reply
            0
            • C chauteen

              Thanks for your reply first. For I am trying your way, to read the entire file and then write the whole data back.(the work I want to do is store 8 spin vlaue to a file, and update when the user click and change spin value.) but I use a brute force way, for I don't know how to read data in CString:confused: I declare an BYTE array, called buffer[8], and in the dialog's init, I read in the file fread( buffer, sizeof( BYTE ), 8, filespin ); and in the spin message, I add fseek(filespin, 0, SEEK_SET); fprintf( filespin, "%s", buffer ); I've also tried fwrite fwrite( buffer, sizeof( BYTE ), 8, filespin ); both failed the output file will contain some strange code, like slash , camma or something. I try to show the readin buffer text on a editbox, and it already contain a unexpected slash and the end.:confused: It seems the read in have something wrong already, not to mention write data back. Can you suggest me some smart or "correct" way to do? Thank you very much. chauteen

              V Offline
              V Offline
              V 0
              wrote on last edited by
              #7

              I suppose you are using MFC? Then you know that a spinbutton is a textbox attached with a spincontrol. Get a handle to your textboxes (assign a control variable or via GetDlgItem) eg your handlers are called: edit1, edit2, ... edit8 and assign CStrings eg. string1 -> string8 then you can do when onchangeedit1 occurs. edit1.GetWindowText(string1); etc... then print them with fprintf and read them with freadf. If you don't use CString use char or a char array, not BYTE. (a BYTE can be anything). You could try casting the BYTE to a char, but I'm not sure what it will give. I think the reason of your strange results is that a BYTE will not be interpreted as a character, but that just a guess. if the char array doesn't seem to work you probably forgot the "\o" character. You can find this stuff on MSDN. Look on CString, GetWindowText (SetWindowText) etc. (note: if you can't assign a control variable do this: CWnd* pWnd; pWnd = (CWnd*)GetDlgItem(IDC_NAMEOF_EDIT_BOX); pWnd->GetWindowText(.....) .... ) "If I don't see you in this world, I'll see you in the next one... and don't be late." ~ Jimi Hendrix

              A 1 Reply Last reply
              0
              • V V 0

                I suppose you are using MFC? Then you know that a spinbutton is a textbox attached with a spincontrol. Get a handle to your textboxes (assign a control variable or via GetDlgItem) eg your handlers are called: edit1, edit2, ... edit8 and assign CStrings eg. string1 -> string8 then you can do when onchangeedit1 occurs. edit1.GetWindowText(string1); etc... then print them with fprintf and read them with freadf. If you don't use CString use char or a char array, not BYTE. (a BYTE can be anything). You could try casting the BYTE to a char, but I'm not sure what it will give. I think the reason of your strange results is that a BYTE will not be interpreted as a character, but that just a guess. if the char array doesn't seem to work you probably forgot the "\o" character. You can find this stuff on MSDN. Look on CString, GetWindowText (SetWindowText) etc. (note: if you can't assign a control variable do this: CWnd* pWnd; pWnd = (CWnd*)GetDlgItem(IDC_NAMEOF_EDIT_BOX); pWnd->GetWindowText(.....) .... ) "If I don't see you in this world, I'll see you in the next one... and don't be late." ~ Jimi Hendrix

                A Offline
                A Offline
                Anonymous
                wrote on last edited by
                #8

                First thanks for your help. Right now, I use GetWindowText to get the edit box text, and over write the "whole" data at every onchangeedit message.(Still a kind of lazy;P) Any way it works. I'm wondering if the situation happened with reading and modifyind large file. how could one read out the whole data, and write it back at every edit change just because not be able to use fseek to move the file pointer to a certain "line". (for fprint can only move the file pointer to certain "byte " from origin):doh: chauteen

                V 1 Reply Last reply
                0
                • A Anonymous

                  First thanks for your help. Right now, I use GetWindowText to get the edit box text, and over write the "whole" data at every onchangeedit message.(Still a kind of lazy;P) Any way it works. I'm wondering if the situation happened with reading and modifyind large file. how could one read out the whole data, and write it back at every edit change just because not be able to use fseek to move the file pointer to a certain "line". (for fprint can only move the file pointer to certain "byte " from origin):doh: chauteen

                  V Offline
                  V Offline
                  V 0
                  wrote on last edited by
                  #9

                  What we do here at work is to add "metadata" in the file, but still we always read the entire file into CStrings. You can do something like: "#value1|value2|...|valuen#" Where # = beginning - end and the | is a delimiter. Note that 1 character is 1 byte long, this means you can load about 13000 lines (1 line ~ 80 characters) for each MegaByte of memory. Normally you have about 512 Mb, not to mention virtual memory. Point is, it's really no problem loading the file into memory. The reading takes time, but as you may have noticed, Word, Excel, Notepad, ... all take some time to load their text. "If I don't see you in this world, I'll see you in the next one... and don't be late." ~ Jimi Hendrix

                  C 1 Reply Last reply
                  0
                  • V V 0

                    What we do here at work is to add "metadata" in the file, but still we always read the entire file into CStrings. You can do something like: "#value1|value2|...|valuen#" Where # = beginning - end and the | is a delimiter. Note that 1 character is 1 byte long, this means you can load about 13000 lines (1 line ~ 80 characters) for each MegaByte of memory. Normally you have about 512 Mb, not to mention virtual memory. Point is, it's really no problem loading the file into memory. The reading takes time, but as you may have noticed, Word, Excel, Notepad, ... all take some time to load their text. "If I don't see you in this world, I'll see you in the next one... and don't be late." ~ Jimi Hendrix

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

                    hi V. I'm sorry keeping on bothering you. I agree with you, it is ok to load the whole data to memory. But I need to write data back and close the file at every editchange, because the file will be accessed by another class. Fortunately, I have only 8 data need to handle, the speed is compltely fine with me. My tesk is like this: I use MFC to make a dialog. I have serveral tabs with about 8 spins on each of them. and I add these tabs on a base dailog. I send the spin value out on a master query(I'm slave on the bus. I cann't send data out on my own. I need to wait the query command.) So I decide to store the tabs spin values in several files(every tab has it's own file), and open a serial port on the base port. When the user change the spin value, he only change the file, but doesn't send it out. When the master polling, I send the file data to master.(the polling speed is faster than the user's finger to click spin, of course) Will my idea work? One more ask V. wrote: "#value1|value2|...|valuen#" if I make my file like this: 10 15 20 when I fread them, CString will treat 10 to be one byte, or treat 1 as one byte and 0 as teh second byte? Many thanks for your help beforehan. slow-witted chauteen

                    V 1 Reply Last reply
                    0
                    • C chauteen

                      hi V. I'm sorry keeping on bothering you. I agree with you, it is ok to load the whole data to memory. But I need to write data back and close the file at every editchange, because the file will be accessed by another class. Fortunately, I have only 8 data need to handle, the speed is compltely fine with me. My tesk is like this: I use MFC to make a dialog. I have serveral tabs with about 8 spins on each of them. and I add these tabs on a base dailog. I send the spin value out on a master query(I'm slave on the bus. I cann't send data out on my own. I need to wait the query command.) So I decide to store the tabs spin values in several files(every tab has it's own file), and open a serial port on the base port. When the user change the spin value, he only change the file, but doesn't send it out. When the master polling, I send the file data to master.(the polling speed is faster than the user's finger to click spin, of course) Will my idea work? One more ask V. wrote: "#value1|value2|...|valuen#" if I make my file like this: 10 15 20 when I fread them, CString will treat 10 to be one byte, or treat 1 as one byte and 0 as teh second byte? Many thanks for your help beforehan. slow-witted chauteen

                      V Offline
                      V Offline
                      V 0
                      wrote on last edited by
                      #11

                      Well actually it depends on which coding you use, but 90% of all uses are ASCII which (in modern times) takes 1 byte per character. A character is not only a, b, c, ... or 0-9, but also a space, tab, return ,... so 10 would be 2 bytes. (a byte stands for BY EIGHT, 8 bits) (and 1 byte for return and I even think 1 byte for the new line, but I'm not sure the fread will read them) For your idea, yes it will work I think, but I would consider putting them in 1 file, this is however just a detail. My experience is that the boss will not tire himself too much by checking how you did it, he just wants it working (no matter what dirty tricks :-)) good luck. "If I don't see you in this world, I'll see you in the next one... and don't be late." ~ Jimi Hendrix

                      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