Archived

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

BlueDev

Reading blocks of data in stdio

Recommended Posts

BlueDev    126
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
BlueDev    126
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