Skip to content

Instantly share code, notes, and snippets.

@pppoe
Created April 26, 2013 17:22
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 pppoe/5468844 to your computer and use it in GitHub Desktop.
Save pppoe/5468844 to your computer and use it in GitHub Desktop.
fread fwrite fprintf fscanf, C-style strtok and C++ getline for tokenize
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
/* Binary IO*/
/*
FILE *fd = fopen("./test-binary", "w");
if (fd)
{
int arr[] = { 1, 2, 3};
fwrite(arr, sizeof(int), 3, fd);
fclose(fd);
}
FILE *fd_read = fopen("./test-binary", "r");
if (fd_read)
{
const int size = 3;
int arr[size];
fread(arr, sizeof(int), 3, fd_read);
for (int i = 0; i < size; i++)
{
cout << arr[i] << endl;
}
fclose(fd_read);
}
*/
/* Text IO */
FILE *fd = fopen("./test-format", "w");
if (fd)
{
fprintf(fd, "Formatted %d %d %d\n", 1, 2, 3);
fclose(fd);
}
FILE *fd_read = fopen("./test-format", "r");
if (fd_read)
{
int arr[3];
fscanf(fd, "Formatted %d %d %d\n",
&arr[0],
&arr[1],
&arr[2]);
for (int i = 0; i < 3; i++)
{
cout << arr[i] << endl;
}
fclose(fd_read);
}
return 0;
}
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
string input = "kljfda,flaksdjf,fkladf,ljioqwe,dasf";
stringstream ss;
ss << input;
vector<string> tokens;
string output;
while (std::getline(ss, output, ','))
{
tokens.push_back(output);
}
for (string& s : tokens)
{
cout << s << endl;
}
return 0;
}
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <cstring>
using namespace std;
int main()
{
char buffer[] = "kljfda,flaksdjf|fkladf,ljioqwe,dasf";
vector<string> tokens;
char *token = strtok(buffer, ",|");
while (token)
{
tokens.push_back(string(token));
token = strtok(NULL,",|");
}
for (string& s : tokens)
{
cout << s << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment