Visualizzazione dei risultati da 1 a 4 su 4
  1. #1
    Utente di HTML.it
    Registrato dal
    Jun 2003
    Messaggi
    4,826

    [c++]file testo e binari

    ciao.
    sto tentando di aprire un file in lettura ma ottengo una stringa con degli sporchi alla fine:
    codice:
    pFile = fopen ( strFilename.c_str() , "rb" );
    	fseek (pFile , 0 , SEEK_END);
    	lSize = ftell(pFile);
    	rewind (pFile);
    
    	buffer = new char[lSize];
    	buffer[0] = '\0';
    	
    	// copy the file into the buffer:
    	result = fread (buffer,1,lSize,pFile);
    
    	int i = 0;
    	char pa;
    	string strx = "";
    	while(pa = buffer[i])
    	{	
    		strx += pa;
    		i++;
    	}
    	
    	fclose (pFile);
    	free (buffer);
    	
    	return 0;
    la lunghezza del file è 12(lSize)
    ma la stringa strx si estende per 20 caratteri ,vengono aggiunti dei caratteri strani alla fine non capisco .

    Ho letto che c'è una differenza tra aprire un file binario e un file di testo puo essere quello?
    qual è la differenza di lettura tra un file di testo e un file binario?
    grazie.

  2. #2
    Utente di HTML.it L'avatar di shodan
    Registrato dal
    Jun 2001
    Messaggi
    2,381
    Leggi la documentazione di fread e ti accorgerai che result non è messo li a caso.
    Per quanto riguarda i file, l'unica differenza è il \n che in un file di testo è usato per segnalare il fine riga, nel file binario è un byte come gli altri.
    This code and information is provided "as is" without warranty of any kind, either expressed
    or implied, including but not limited to the implied warranties of merchantability and/or
    fitness for a particular purpose.

  3. #3
    Utente di HTML.it
    Registrato dal
    Jun 2003
    Messaggi
    4,826
    scusami shodan , ho provato questo codice :
    codice:
    // test.cpp : Defines the entry point for the console application.
    //
    
    #include "stdafx.h"
    
    int _tmain(int argc, _TCHAR* argv[])
    {
     FILE * pFile;
      long lSize;
      char * buffer;
      size_t result;
    
      pFile = fopen ( "c:\\errors.txt" , "rb" );
      if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
    
      // obtain file size:
      fseek (pFile , 0 , SEEK_END);
      lSize = ftell (pFile);
      rewind (pFile);
    
      // allocate memory to contain the whole file:
      buffer = (char*) malloc (sizeof(_TCHAR)*lSize);
      if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
    
      // copy the file into the buffer:
      result = fread (buffer,1,lSize,pFile);
      if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
    
      /* the whole file is now loaded in the memory buffer. */
    
      // terminate
      fclose (pFile);
      free (buffer);
      return 0;
    
    	return 0;
    }
    copiato e incollato , ma mi da sempre quegli sporchi di cui ti parlavo:
    buffer = (char*) malloc (sizeof(char)*lSize);
    mi da un buffer con questo contenuto:
    "ÍÍÍÍÍÍÍÍÍÍÍÍýýýý««««««««"
    mentre quando carico il buffer:
    result = fread (buffer,1,lSize,pFile);
    mi ritorna 12 e non da nessun errore , solo che il buffer ha questo contenuto:
    "aaaa aab endýýýý««««««««"
    invece di :
    "aaaa aab end"

    ho provato a ricercare TCHAR(che è l'unica cosa che è cambiata dall esempio) su google perchè pensavo che potesse avere un size differente da char e ho provato a mettere TCHAR il buffer e...
    buffer = (TCHAR*) malloc (sizeof(TCHAR)*lSize);

    ma non è cambiato niente .
    ma cosa puo essere ?


    grazie.

  4. #4
    Utente di HTML.it L'avatar di shodan
    Registrato dal
    Jun 2001
    Messaggi
    2,381
    Invece di che ti procura solo un bernoccolo, leggi bene cosa dice la documentazione di fread()


    The total number of elements successfully read is returned as a size_t object, which is an integral data type.
    If this number differs from the count parameter, either an error occured or the End Of File was reached.

    You can use either ferror or feof to check whether an error happened or the End-of-File was reached.
    Cioè ritorna il numero di caratteri letti, che può essere anche minore di quello che richiedi (o zero se non legge niente), il che, però, non è un errore.

    Tra l'altro fai un altro errore usando _TCHAR. fread() legge sempre e comunque dei char, quindi la dimensione del buffer deve tenerne conto se _TCHAR == wchar_t.
    codice:
    result = fread (buffer,1,lSize* sizeof(_TCHAR) ,pFile );
    Considera poi che lo 0 in una lettura binaria è un valore valido, quindi il valore di ritorno della fread non puoi usarlo per intervenire in maniera diretta sul buffer trattandolo con le funzioni di stringa del C.

    In definitiva devi modificare il codice in questo modo.
    codice:
      buffer = (char*) malloc (lSize+1); // +1 per sicurezza.
    
      if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
    
      // copy the file into the buffer:
      bytesRead = fread (buffer,lSize,1,pFile);
      if (bytesRead == 0 ) {
          fputs ("Reached end of file",stderr); 
      }
    
      for (i = 0; i < bytesRead; i++) {
          fputc( buffer[i], stdout));      
      }
    P.S.
    Nel topic parli di C++, nel post usi il filesystem del C. Qualche motivo particolare?
    This code and information is provided "as is" without warranty of any kind, either expressed
    or implied, including but not limited to the implied warranties of merchantability and/or
    fitness for a particular purpose.

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.