Thread: Write and Read in a TXT.

  1. #1
    Registered User
    Join Date
    Aug 2008
    Posts
    23

    Write and Read in a TXT.

    I made this small program to create and read text files,
    It creates normal, but at the time to read, it shows right things on the screen, but give me a error later.
    Anyone know what can be?

    Code:
    // Teste.cpp : Defines the entry point for the console application.
    //
    
    #include "stdafx.h"
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    typedef struct _Contato 
    {
    	int codigo;
    	char nome[30];
    	char email[100];
    } Contato;
    
    int main() 
    {
    	// Cria ponteiro para arquivo
    	FILE *agenda;
    	// Cria nova variavel do tipo Contato
    	Contato addcont;
    	// Variavel temporaria para gravar uma linha no arquivo
    	char temp[4096];
    	int ctrl;
    
    	// Inicia o Menu
    	ctrl = 0;
    
    	while (ctrl != 3)
    	{
    		system("cls");
    		printf("\n AGENDA TELEFONICA");
    		printf("\n\n 1 - Inserir na lista");
    		printf("\n 2 - Remover da lista");
    		printf("\n 3 - Sair");
    		printf("\n\n ==> ");
    		scanf("%d",&ctrl);
    		system("cls");
    
    		// Incluir
    		if (ctrl==1)
    		{
    			// Inicia os valores
    			addcont.codigo = 1;
    			fflush(stdin);
    			printf(" Entre com o nome: ");
    			gets(addcont.nome);
    			fflush(stdin);
    			printf(" Entre com o e-mail: ");
    			gets(addcont.email);
    
    			// Abre novo arquivo para operacoes de escrita e gravacao (a+)
    			// Caso o arquivo nao exista ele cria, caso ele exista
    			// As gravacoes serao concatenadas no final do arquivo
    			agenda = fopen("agenda.txt", "a+");
    
    			// Importante: Testar se o ponteiro foi criado
    			if (!agenda) 
    			{
    				printf("Erro: Nao foi possivel abrir/criar o arquivo\n");
    				exit(0);
    			}
    
    			// Monta a linha para gravar no arquivo;
    			sprintf(temp, "%d;%s;%s\r\n", addcont.codigo, addcont.nome, addcont.email);
    			// Faz a gravacao dos dados no arquivo no formato CSV (Separado por ";")
    			fputs(temp, agenda);
    
    			// Fecha ponteiro do arquivo e evita que dados sejam corrompidos
    			fclose(agenda);			
    		}
    
    		// Ler
    		if (ctrl==2)
    		{
    			// Abre novo arquivo para leitura (r = read)
    			agenda = fopen("agenda.txt", "r");
    
    			// Importante: Testar se o ponteiro foi criado
    			if (!agenda) 
    			{
    				printf("Erro: Nao foi possivel abrir o arquivo\n");
    				exit(0);
    			}
    
    			// Enquanto o final do arquivo nao chega... fica no loop
    			while (!feof(agenda)) 
    			{
    				// O fgets le uma linha de tamanho 4096 e armazena no temp
    				// do ponteiro de arquivo agenda
    				fgets(temp, 4096, agenda);
    
    				// A funcao atoi converte uma string passada para inteiro
    				// A funcao strtok divide uma string em tokens (partes)
    				//  Obs.: Apenas passar a string para o strtok na primeira chamada
    				//        as outras devem ter NULL ate q a string inteira seja dividida
    				addcont.codigo = atoi(strtok(temp, ";\r\n"));
    				strcpy(addcont.nome, strtok(NULL, ";\r\n"));
    				strcpy(addcont.email, strtok(NULL, ";\r\n"));
    
    				printf("| %3d | %30s | %30s |\n", addcont.codigo, addcont.nome, addcont.email);
    
    			}
    			// Fecha ponteiro do arquivo e evita que dados sejam corrompidos
    			fclose(agenda);
    			system("pause");
    		}	
    	}
    	//return 0;
    }

  2. #2
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    It is most likely because of your last loop where you are controlling the loop condition with feof. That is not a good idea.

    Read more about it here:
    Cprogramming.com FAQ > Why it's bad to use feof() to control a loop

    If you say your program prints correctly and then crashes it is probably because it reads the EOF in a subsequent iteration and crashes when it attempts to get 4096 chars.

  3. #3
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Code:
    fflush(stdin);
    fflush is undefined for input streams/buffers.



    Code:
    gets(addcont.email);
    There are better choices than gets. As an example you might try fgets for example.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. open read write close
    By mercuryfrost in forum C Programming
    Replies: 7
    Last Post: 08-23-2009, 05:27 PM
  2. Read from txt and write in an external program
    By sombrancelha in forum C Programming
    Replies: 8
    Last Post: 06-01-2009, 09:04 PM
  3. read write lock in C#
    By George2 in forum C# Programming
    Replies: 0
    Last Post: 04-16-2008, 08:49 AM
  4. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  5. write(), read()
    By RedRum in forum C++ Programming
    Replies: 5
    Last Post: 06-09-2002, 11:45 AM