开发者

Outputting a string variable into a text file in HEX format

开发者 https://www.devze.com 2023-02-07 01:26 出处:网络
I\'m stuck with a problem that I cannot solve. So what i need is following: I need to make a program that receives one string input and converts it to hex and after that it saves it into a file.

I'm stuck with a problem that I cannot solve. So what i need is following: I need to make a program that receives one string input and converts it to hex and after that it saves it into a file. If the file isn't created, it should, but if there is one already it should continue writing to the same (i guess "a+" parameter is what i need here right? )

So an example. I execute the program. Asks me to input some words. I type "stack" and it returns me this "73 74 61 63 6B" which is correct. I've done that with this algorithm

#include <cstdio>
#include <cstdlib>
#include <string>
#include <iostream>
using namespace std;
int main(){
 string a;
 cin >> a;
 for( int i = 0; i < a.size(); i++ )
  printf( "%hX ", a[i] );
 cout << endl;
 system( "pause" );
 return 0;
}

That is all fine but I need that outputed in a text file. I used this:

for( int i = 0; i < a.size(); i++ ) 
     {  
      fprintf(pFile, "%hX ", a[i]); 
     }

But it doesn't work. Can i get help with this one, thank you!

The full code, sor开发者_开发百科ry I'm having problems with code samples I hope you don't mind pastebin link http://pastebin.com/3u1mfg8n


You are learning C++ so why not use file streams?

#include <fstream>
#include <iomanip>

using namespace std;

int main () {
  // Read your string as before
  fstream fs;
  fs.open ("hex.txt", fstream::out | fstream::app); // app = append to file
  for(int i=0; i<a.size(); ++i) 
  {  
    fs << hex << static_cast<int>(a[i]) << " ";
  }
  fs.close();
  return 0;
}


I have tested your code and it is working correctly. It creates a file called Personal Shop Codes.txt in the directory it is run from. I expect the problem is that your program is not being run from the directory you expect it to be run from, so your output file is merely misplaced. This can often be the case when executing your program inside an IDE.


You need to use fopen() and assign that to your FILE pointer first:

FILE *pFile;
pFile = fopen("output.txt","w");

And then close the file when your program has finished writing to it:

fclose(pFile);


This will convert each byte in the string (each character that is) into its 2-character hex encoding:

for(int i = 0; i < a.size(); i++)
{
    printf("%2.2X ", a[i]);
}

If you want to store it:

std::string b = "";
for (int i = 0; i < a.size(); ++i)
{
    char tmp[3] = {0};
    sprintf(tmp, "%2.2X", a[i]);
    b += tmp;
}

Then you can write the entire b string out to the file easily.

0

精彩评论

暂无评论...
验证码 换一张
取 消