Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

BlueDev

Reading blocks of data in stdio

This topic is 5405 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, Im currently loading a file with stdio, example below, and im trying to write my code so that I can read a block of 15 characters per buffer, now of course I dont need to write each buffer to its own char, I just need to be able to see the next 15, and the next so on and so forth. I was wondering if someone could look at my code and see if I am needing a simple code to get this to work because at the moment im only getting the same 15 characters over and over again:
#include <iostream.h>
#include <stdlib.h>
#include <stdio.h>

unsigned long getfilesize(FILE *file) {
	unsigned long i = 0;

	rewind(file);

	while (!feof(file)) {
		fgetc(file);
		i++;
	}
return i;
}

void main() {
	FILE *file;
	long lSize, bufSize;
	int maxSize = 15;
	char *buffer;

	file=fopen("C:\\test.txt", "r");
		lSize = (unsigned long)getfilesize(file);

		if( lSize > maxSize ) {
			bufSize = (lSize / maxSize);
			rewind(file);
			for(int i = 0; i < bufSize; i++ ) {
				fseek (file, 0, SEEK_SET);
				rewind(file);

				buffer = (char*) malloc (maxSize - 4);
				if (buffer == NULL) exit (2);

				fread(buffer,1,maxSize,file);

				cout << buffer;
				cout << endl;
			}
		}
	fclose(file);
}
Thanks again. - BlueDev
   BlueDev Net
Advertisement
before your malloc, you are rewinding the file (twice actually) rewind(file) and fseek(file, 0, SEEK_SET) do the same thing

Share this post


Link to post
Share on other sites
Ah, ok. hehe my bad so if I get rid of both I start to read more than 15 characters, like 25 or 30, why is that?

edit: nevermind I see what was wrong, I still had an extra rewind, thanks all.

- BlueDev

[edited by - BlueDev on August 31, 2003 11:05:57 PM]

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!