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. Problem with read in CFile class

Problem with read in CFile class

Scheduled Pinned Locked Moved C / C++ / MFC
helpgraphics
13 Posts 4 Posters 2 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.
  • A antonio343

    I have two function to save/load information from/in a file. My problem is that

    for(int p=0;p
    This line dont read well, only read the first date, and after read rubbish.

    f.ReadString(ausente_b);

    In this line read a empty CString

    and so on..

    Overcoat fail when read CString variable

    This is my function:

    int CAdestView::PegarVariables(void)
    {
    //FILE *fichero; // Puntero a un fichero
    int tamano_b; // tamano temporal
    int x=0; // elementos copiados
    CString nombre_b; // nombre temporal
    double dato_b=0; // datos temporal para introducirlo en un vector
    double *datos_b; // vector de datos si la variable no es de texto
    CString *datostxt_b; // vector de Cstring si la variable es de texto
    CString datotxt_b; // datos temporal de una variable de texto
    CString ausente_b; // dato ausente temporal
    int escala_b=0; // escala temporal
    CString etiqueta_b; // etiqueta temporal
    CString labels_b; // labels temporal
    int precision_b=0; // precision temporal
    int tipo_b=0; // tipo temporal

    CString error;			// Cadena para mostrar error 
    INT\_PTR tam\_vars;
    int n = 1;				// Entero para formar el nuevo nombre de la variable
    CString aux\_nombre;		// Cadena que almacena los nombres que formamos como posibles
    CString aux\_nombre\_lista;	// Cadena que almacena los nombres leídos del control lista
    bool salir = false;		// Nos indica si ya hemos encontrado un nuevo nombre válido
    bool encontrado = false;	// Nos indica si hemso encontrado una variable con el mismo nombre
    CStdioFile f;
    // Se obtiene un puntero de la clase view
    CAdestDoc\* pDoc = GetDocument();
    ASSERT\_VALID(pDoc);
    
    // Se abre el fichero temporal para lectura
    CString path= GetUserHomeDir() + \_T("\\\\temporal.dat");
    
    f.Open( path, CFile::modeReadWrite | CFile::typeBinary);
    
    if (f == NULL)
    {
    	MessageBox (\_T("fallo"));
    	return 0;
    }
    // Situamos el puntero del fichero
    //fseek(fichero,sizeof(int),SEEK\_SET);
    f.SeekToBegin();
    tam\_vars = pDoc->Variables.GetSize ();
    // Vemos si existe algun dato a pegar, el primero es el numero
    // de datos a pegar
    // Si no hay datos devolmemos 0 y salimos
    
    	if(f.Read(&x,sizeof(x))<0)
    	return 0;
    
    // Bucle que recorre todos los elementos a pegar
    for(int h=0;h<x;h++)
    {
    	// Leemos del fichero el tipo de la variable
    	f.Read(&tipo\_b,sizeof(tipo\_b));
    	// Leem
    
    D Offline
    D Offline
    David Crow
    wrote on last edited by
    #3

    In addition to Richard's suggestion, narrow the problem down to just a small handful of lines. Upwards of 95% of the code you've shown is not part of the problem scope (i.e., is irrelevant).

    "One man's wage rise is another man's price increase." - Harold Wilson

    "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

    "Show me a community that obeys the Ten Commandments and I'll show you a less crowded prison system." - Anonymous

    A 1 Reply Last reply
    0
    • D David Crow

      In addition to Richard's suggestion, narrow the problem down to just a small handful of lines. Upwards of 95% of the code you've shown is not part of the problem scope (i.e., is irrelevant).

      "One man's wage rise is another man's price increase." - Harold Wilson

      "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

      "Show me a community that obeys the Ten Commandments and I'll show you a less crowded prison system." - Anonymous

      A Offline
      A Offline
      antonio343
      wrote on last edited by
      #4

      I did other example to prove somthing, I did :

      CStdioFile f;

      	// Se abre el fichero para escritura
      CString path= GetUserHomeDir() + \_T("\\\\temporal.txt");
      f.Open(path, CFile::modeCreate | CFile::modeWrite | CFile::typeText);
      
      double a=9.8;
      CString b=\_T("hello");
      
      f.WriteString(b);
      f.Write(&a,sizeof(double));
      
      f.Close();
      

      I see the content from the file, and only wrote hello. This is the content from the file: hello™™™™™#@

      L 1 Reply Last reply
      0
      • A antonio343

        I did other example to prove somthing, I did :

        CStdioFile f;

        	// Se abre el fichero para escritura
        CString path= GetUserHomeDir() + \_T("\\\\temporal.txt");
        f.Open(path, CFile::modeCreate | CFile::modeWrite | CFile::typeText);
        
        double a=9.8;
        CString b=\_T("hello");
        
        f.WriteString(b);
        f.Write(&a,sizeof(double));
        
        f.Close();
        

        I see the content from the file, and only wrote hello. This is the content from the file: hello™™™™™#@

        L Offline
        L Offline
        Lost User
        wrote on last edited by
        #5

        antonio343 wrote:

        I see the content from the file, and only wrote hello.

        The above code shows you follow the word "hello" with a double value, so the file content is correct. You also do not show any code to read the file so I am still not sure what your problem is.

        Unrequited desire is character building. OriginalGriff

        A 1 Reply Last reply
        0
        • L Lost User

          antonio343 wrote:

          I see the content from the file, and only wrote hello.

          The above code shows you follow the word "hello" with a double value, so the file content is correct. You also do not show any code to read the file so I am still not sure what your problem is.

          Unrequited desire is character building. OriginalGriff

          A Offline
          A Offline
          antonio343
          wrote on last edited by
          #6

          The content from the file isn't correct!!!!! I wrote hello and 9.8 and it isn't the content of the file. In adittion, I made a method to read the file

          CStdioFile f;
          CString b;
          double a;

          	// Se abre el fichero para escritura
          CString path= GetUserHomeDir() + \_T("\\\\temporal.txt");
          f.Open(path, CFile::modeRead | CFile::typeText);
          
          f.ReadString(b);
          f.Read(&a,sizeof(double));
          
          f.Close();
          

          And it dont read well. It read hello#@ and in the other variable, read rubbish

          L 1 Reply Last reply
          0
          • A antonio343

            The content from the file isn't correct!!!!! I wrote hello and 9.8 and it isn't the content of the file. In adittion, I made a method to read the file

            CStdioFile f;
            CString b;
            double a;

            	// Se abre el fichero para escritura
            CString path= GetUserHomeDir() + \_T("\\\\temporal.txt");
            f.Open(path, CFile::modeRead | CFile::typeText);
            
            f.ReadString(b);
            f.Read(&a,sizeof(double));
            
            f.Close();
            

            And it dont read well. It read hello#@ and in the other variable, read rubbish

            L Offline
            L Offline
            Lost User
            wrote on last edited by
            #7

            antonio343 wrote:

            The content from the file isn't correct!

            Yes it is, you do not understand what you are writing. The line:

            f.Write(&a,sizeof(double));
            

            writes the double value exactly as it is held in memory as a binary value 8 bytes wide. If you wish to convert it to a textual representation then you need to format it into a text string with sprintf() or CString, using the appropriate format codes.

            Unrequited desire is character building. OriginalGriff

            A 1 Reply Last reply
            0
            • L Lost User

              antonio343 wrote:

              The content from the file isn't correct!

              Yes it is, you do not understand what you are writing. The line:

              f.Write(&a,sizeof(double));
              

              writes the double value exactly as it is held in memory as a binary value 8 bytes wide. If you wish to convert it to a textual representation then you need to format it into a text string with sprintf() or CString, using the appropriate format codes.

              Unrequited desire is character building. OriginalGriff

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

              ok.. But I don't need to show. In the first function that I post here, I need to copy the value of variable in a file, and after load the value in variable, I dont know how to do it, becouse I try with fread/fwrite, CFile class, CStdio class, and I don't get something. The problem is the variable are several kind of dates, CString, double, int... but I think that the main problem is save and load CString kind.

              L 1 Reply Last reply
              0
              • A antonio343

                ok.. But I don't need to show. In the first function that I post here, I need to copy the value of variable in a file, and after load the value in variable, I dont know how to do it, becouse I try with fread/fwrite, CFile class, CStdio class, and I don't get something. The problem is the variable are several kind of dates, CString, double, int... but I think that the main problem is save and load CString kind.

                L Offline
                L Offline
                Lost User
                wrote on last edited by
                #9

                There is no problem with what you suggest, you merely need to ensure that what you try to read back exactly mirrors what you write. This means that you must read back the exact number of bytes that you have written in the first place. With elementary items (int, double, char etc.) this is not difficult, but with strings you need to add some extra information to know how many characters to read in; you could do this by adding an integer in front of the string that specifies its length. Alternatively, use one of the formatting functions to convert all your data to string items and use some form of field separation (e.g. CSV, XML) to write in lines of text which you can then reconvert when reading back.

                Unrequited desire is character building. OriginalGriff

                A 1 Reply Last reply
                0
                • L Lost User

                  There is no problem with what you suggest, you merely need to ensure that what you try to read back exactly mirrors what you write. This means that you must read back the exact number of bytes that you have written in the first place. With elementary items (int, double, char etc.) this is not difficult, but with strings you need to add some extra information to know how many characters to read in; you could do this by adding an integer in front of the string that specifies its length. Alternatively, use one of the formatting functions to convert all your data to string items and use some form of field separation (e.g. CSV, XML) to write in lines of text which you can then reconvert when reading back.

                  Unrequited desire is character building. OriginalGriff

                  A Offline
                  A Offline
                  antonio343
                  wrote on last edited by
                  #10

                  I tried to do this:

                  int nLength = b.GetLength() + 1; // string lenght in characters
                  int nBytes = nLength * sizeof(TCHAR); // buffer size in bytes
                  f.Write(&nLength, sizeof(int)); // write string length
                  f.Write(b, nBytes); // write string
                  f.Write(&a,sizeof(double));

                  And the problem is the same, this is the content of the file:

                  h o l a C a r a c o l a š™™™™™#@

                  C L 2 Replies Last reply
                  0
                  • A antonio343

                    I tried to do this:

                    int nLength = b.GetLength() + 1; // string lenght in characters
                    int nBytes = nLength * sizeof(TCHAR); // buffer size in bytes
                    f.Write(&nLength, sizeof(int)); // write string length
                    f.Write(b, nBytes); // write string
                    f.Write(&a,sizeof(double));

                    And the problem is the same, this is the content of the file:

                    h o l a C a r a c o l a š™™™™™#@

                    C Offline
                    C Offline
                    Chuck OToole
                    wrote on last edited by
                    #11

                    "Here is the content of the file"... Just how are you getting that output to show us? Is that from some editor or file dump utility? If you write a file containing some binary data (and you do, both 'nLength' and 'a' are written to the file as plain binary data), and then you ask an editor to display the content of the file, of course you are going to get garbage. Editors make the reasonable assumption that the entire data file is 'char' and will attempt to interpret the file in that way, rendering all the characters into some printable form, including trash characters as you observe. For binary data, editors and other display programs are inappropriate for looking at the contents to see if it is correct. Raw binary file dumpers are the best for that, then you can see every byte.

                    1 Reply Last reply
                    0
                    • A antonio343

                      I tried to do this:

                      int nLength = b.GetLength() + 1; // string lenght in characters
                      int nBytes = nLength * sizeof(TCHAR); // buffer size in bytes
                      f.Write(&nLength, sizeof(int)); // write string length
                      f.Write(b, nBytes); // write string
                      f.Write(&a,sizeof(double));

                      And the problem is the same, this is the content of the file:

                      h o l a C a r a c o l a š™™™™™#@

                      L Offline
                      L Offline
                      Lost User
                      wrote on last edited by
                      #12

                      So what is the problem? Do you think your binary values are going to somehow magically transform themselves to textual representations? As I said before this content is correct and if you read it back using the information that you used to write it out you will have no problems. Or, you could adopt my other suggestion of converting everything to strings and using CSV, XML or some other system to manage your data.

                      Unrequited desire is character building. OriginalGriff

                      A 1 Reply Last reply
                      0
                      • L Lost User

                        So what is the problem? Do you think your binary values are going to somehow magically transform themselves to textual representations? As I said before this content is correct and if you read it back using the information that you used to write it out you will have no problems. Or, you could adopt my other suggestion of converting everything to strings and using CSV, XML or some other system to manage your data.

                        Unrequited desire is character building. OriginalGriff

                        A Offline
                        A Offline
                        antonio343
                        wrote on last edited by
                        #13

                        But the file isn't binary, it is text file, and dont show well the content I'm sorry, you are right, the content is read well Thank you so much, finally I get to do run well my function

                        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