Skip to content

Instantly share code, notes, and snippets.

@RenatoUtsch
Created November 28, 2012 17:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RenatoUtsch/4162870 to your computer and use it in GitHub Desktop.
Save RenatoUtsch/4162870 to your computer and use it in GitHub Desktop.
C++ STL Stack file loading test
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <stack>
#include "benchmark/benchmark.h"
void test_func(void *data, size_t numBytes)
{
std::stack<char> myStack;
char *testData = (char *) data, *p;
FILE *fp;
for(p = testData; p < testData + numBytes; ++p)
{
try
{
myStack.push(*p);
}
catch(...)
{
printf("ERROR! %lu\n", p - testData);
exit(5);
}
}
if((fp = fopen("test.txt", "w")) == NULL)
{
printf("Error, couldn't open file!");
exit(6);
}
while(!myStack.empty())
{
try
{
fputc(myStack.top(), fp);
myStack.pop();
}
catch(...)
{
printf("ERROR! Couldn't pop item number %lu\n", myStack.size());
exit(7);
}
}
fclose(fp);
}
int main(int argc, char **argv)
{
FILE *fp;
long byteCount, numSteps;
void *fileText;
if(argc != 4)
{
printf("Error! Expected 4 arguments!\n");
return 5;
}
if((fp = fopen(argv[1], "r")) == NULL)
{
printf("Problem with argv[1].\n");
return 1;
}
if((byteCount = strtol(argv[2], NULL, 10)) == 0L)
{
printf("Problem with argv[2].\n");
return 2;
}
if((numSteps = strtol(argv[3], NULL, 10)) == 0L)
{
printf("Problem with argv[3].\n");
return 3;
}
fileText = malloc(byteCount);
if(fread(fileText, 1, byteCount, fp) != (size_t) byteCount)
{
printf("Couldn't read file properly.\n");
return 4;
}
benchmark(test_func, fileText, byteCount, numSteps);
fclose(fp);
free(fileText);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment