Problem passing text to and from text file

edited August 2005 in Internet & Media
I am writing to a text file and have a problem that it writes an extra carriage return at the end of each line (without me telling it to!) and when I read this code back into the program, it refuses to read up to the last line and instead reads up to the line before the penultimate line (2 lines before the end). I'll try and explain more clearly. When I write to the file, I'm writing people's names as a string using the following line of code:
fprintf(winners_fp, "%s", buffer);
where winners_fp is the file pointer to the winners.txt file, and buffer is a 256 character array string holder thingy.

So, let's say that it wrote my name, Andrew Dawson to the file it would write:

Random Person (was already stored in the text file - I am amending the file)
Dawson Andrew
(carraige return here)

Then when I read it in and using the following lines of code:
while (!feof(FP))
   {
      fgets(buffer,100, FP);
      a++;
      printf("Winner number %d was: ",a);
      printf("%s\n", buffer);
   }
It will read the first string, print it out, then loop round (as it's not the end of the file). It then for some reason fails to get anything, so it ends up printing out

Winner number 1 was: Random Person
Winner number 2 was: Random Person

So it thinks it hasn't gotten to the end of the file, but it's not reading the second string in properly and I don't understand why. If I run it multiple times and add more strings, it does the same thing except missing out the last one.

I don't know if I've explained my problem in a way that's understandable, but hopefully I have and someone knows how to fix it! Any help would be much appreciated. Thank you in advance.

I've been playing around with it a bit, but this is the entire program code if it helps:
//	BLOTTO v0.1

//	AJD 0400110

//	Generate random class numbers and decide on a winner of the book

#define CLASS_SIZE 66

#include "lamothe.h"
#include "lamothe.cpp"
#include "cursorVisibility.h"
#include <stdio.h>
#include <time.h>
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <windows.h>
#include <iostream>
#include <iostream.h>
#include <string.h>

using namespace std;

int name,fin=0,winner;

void printlist()
{
	FILE *fp;		// Creates a pointer to a type file

	int a = 0;
	char buffer[100];	// Buffer for imput from file

	if ((fp = fopen("ar0784a.txt", "r")) == NULL)	// Opens the file and checks to see if it succeeded
	{
		fprintf(stderr, "Error opening file.");		// Prints an error message to the screen
		printf("\nError opening the file, press any key to close the program...");
		getch();
		exit (1);	// Exits the program if an error occurs
	}

	while (!feof(fp))	// While NOT at the end of the file
	{
		fgets(buffer,100, fp);	// Get the next string of size 100, from fp, and store it in buffer
		printf("%s", buffer);
		a++;
		if (a == 22 || a == 44 || a == 66) // Pause the list at the screen size, so that the whole list is viewed
		{
			printf("\nPress any key to continue...");
			getche();
			system("cls");
			printf("\n\n\n\n\n\n\n\n\n\n                    This code deserves an A!");
			system("cls");
		}
	}
	fclose(fp);		// Close the file once its not needed
}

void checkwinner()
{
	void printname(void);


	FILE *FP;  // Creates a point to a type file
	int a = 0;
	char buffer[100],surname[20],forename[20],c;
	
	cursorsVisibility(TRUE);
	system("cls");
	if ((FP = fopen("winners.txt", "r")) == NULL) // Opens the file and checks to see if it succeeded
	{
		fprintf(stderr, "Error opening file."); // Prints an error message if it fails
		printf("\nError opening the file, press any key to close the program...");
		getch();
		exit (1); // Exits the program
	}

	do
	{
		c = fscanf(FP, "%s%s",surname,forename); // Grab name 
		a++;
		printf("Winner number %d was: ",a);
		printf("%s %s\n", forename, surname);
		fgets(buffer,100,FP);
	} while (c != EOF);

	fgets(buffer,100,FP);
	printf("The last winner in the list was: %s",buffer);

	fclose(FP); // Close the file as it's no longer needed
	getch();
	fin = 1;
	printname(); // With the global variable set to 1, writes the winner to the winners file
}

void printname()
{

	// Creates pointers to files
	FILE *fp;
	FILE *winners_fp;

	int a = 0;
	char buffer[100];

	if ((fp = fopen("ar0784a.txt", "r")) == NULL)
	{
		fprintf(stderr, "Error opening file ar0784a.txt");

		exit (1);
	}

	if ((winners_fp = fopen("winners.txt", "a")) == NULL)
	{
		fprintf(stderr, "Error opening file winners.txt");

		exit (1);
	}

	while (!feof(fp) )
	{
		a++;
		fgets(buffer,100, fp);
		if (fin == 1)
		{
			name = winner;
			if ((a == name) && (fin ==1))
			{
				fprintf(winners_fp, "%s", buffer);		// Prints the winner's name to the file winners_fp
				fclose(winners_fp);
			}
		}
		if ((a == name) && (fin == 0))
			printf("%s", buffer);
	}
	fclose(fp);
}

void main()
{

	void printlist(void);
	void printname(void);
	void randomcolour(void);

	printlist();
	printname();

	int i;

	Init_Graphics();
	cursorsVisibility(FALSE); // Hides the cursor
	srand(time(NULL)); // Gives "true" random numbers
	Set_Color(14,0); 
	Draw_String(37, 12, "BLOTTO!");
	Sleep(2000);

	//	Fast
	for(i=0; i<39; i++) {
		system("cls");
		Draw_String(30, 12, "");
		randomcolour();
		name = rand()%CLASS_SIZE + 1;
		printname();
		Sleep(50);
	}

	//  Medium
	for(i=0; i<19; i++) {
		system("cls");
		Draw_String(30, 12, "");
		randomcolour();
		name = rand()%CLASS_SIZE + 1;
		printname();
		Sleep(100);
	}

	//  Slowing
	for(i=0; i<9; i++) {
		system("cls");
		Draw_String(30, 12, "");
		randomcolour();
		name = rand()%CLASS_SIZE + 1;
		winner = name;
		printname();
		Set_Color(15,0);
		Sleep(50 + 100*i);
	}

	Draw_String(30, 11, "Winning Student is:");
	Draw_String(30, 13, "Well done!\n");
	randomcolour(); // Gives a random colour for each letter
	Sleep(2000);
	Draw_String(5, 17, "P");
	randomcolour();
	Sleep(250);
	Draw_String(5, 18, "r");
	Sleep(250);
	randomcolour();
	Draw_String(5, 19, "e");
	Sleep(250);
	randomcolour();
	Draw_String(5, 20, "s");
	Sleep(250);
	randomcolour();
	Draw_String(5, 21, "s");
	Sleep(250);
	randomcolour();
	Draw_String(7, 17, "a");
	Sleep(250);
	randomcolour();
	Draw_String(7, 18, "n");
	Sleep(250);
	randomcolour();
	Draw_String(7, 19, "y");
	Sleep(250);
	randomcolour();
	Draw_String(9, 17, "k");
	Sleep(250);
	randomcolour();
	Draw_String(9, 18, "e");
	Sleep(250);
	randomcolour();
	Draw_String(9, 19, "y");
	Sleep(250);
	randomcolour();
	Draw_String(11, 17, "t");
	Sleep(250);
	randomcolour();
	Draw_String(11, 18, "o");
	Sleep(250);
	randomcolour();
	Draw_String(13, 17, "c");
	Sleep(250);
	randomcolour();
	Draw_String(13, 18, "o");
	Sleep(250);
	randomcolour();
	Draw_String(13, 19, "n");
	Sleep(250);
	randomcolour();
	Draw_String(13, 20, "t");
	Sleep(250);
	randomcolour();
	Draw_String(13, 21, "i");
	Sleep(250);
	randomcolour();
	Draw_String(13, 22, "n");
	Sleep(250);
	randomcolour();
	Draw_String(13, 23, "u");
	Sleep(250);
	randomcolour();
	Draw_String(13, 24, "e");
	Sleep(250);
	randomcolour();
	Draw_String(15, 17, ".");
	Sleep(500);
	randomcolour();
	Draw_String(15, 18, ".");
	Sleep(500);
	randomcolour();
	Draw_String(15, 19, ".");
	getch();
	Set_Color(15,0);
	checkwinner();
	cursorsVisibility(FALSE);

	system("cls");
}  // end main

void randomcolour(void)
{ // Function to give a random colour each time a letter is printed

	int colour;

	do
	{
		colour = rand()%7+8;
	}while (colour == 0);
	Set_Color(colour,0);
}

Comments

  • a2jfreaka2jfreak Houston, TX Member
    edited February 2005
    change your [ quote ] [ /quote ] to [ php ] [ /php ] so that the includes can be read and the alignments is better. Or, upload a zip file so that all of your headers can be looked at.

    One thing you should not do is include a .cpp file! Just the .h is required.

    // Edited:
    I said use [ code ] rather than [ php ].
  • sharkydartsharkydart KY Icrontian
    edited August 2005
    I am pretty sure the string datatype, on creation, will add a space to the end of itself. You can then use .rtrim() (or something like that) to remove it. I'm not sure about your situation but it wouldn't surprise me if that is what it is doing when you write your buffer of characters as a string - adding a space to the end.

    That shouldn't be a problem.

    With your fgets are you meaning to try and take the entire line? If the file is being written with multiple strings on each line, your fgets will snatch up 100 characters or the entire line (or up to EOF) whichever comes first - essentially, snatching up more than one string. But, when you then try and use fprintf to print a string from the buffer, you wouldn't be printing a string from a single string, you'd be printing a string from the buffer of chars. So, only up to the first space (i think). Just an idea of what may be going wrong. Make sure you have one string to a line or make sure you are only reading one string at a time. Refer to MSDN library. If you don't have it, go to the website. I have another suggestion if the problem is not related to what I just mentioned, but it is more of a desparate measure.

    But yeah, add .cpp files to the project and include the headers so you can use their functions. Otherwise, it is like if you just copied the .cpp file into the top of the file. I think that causes problems if there are functions or variables declared with the same names.
  • edited August 2005
    If you are in a Windows OS, you need to specify binary mode (b) when using fopen with char buffers if you want to suppress translations.

    CSwett
Sign In or Register to comment.