たとえば、データを逆に印刷するには、次のpopulation = 123456
ように printf します654321
。簡単な方法は次population
のとおりですint
。strrev()
文字列を逆に出力する関数を定義します
あなたのコメントから私が理解しているように、あなたのファイルは次のzipcode
ようpopulation
なものです。
46804 3450103 37215 1337 47906 46849
代替番号を出力ファイルに書き戻したい場合は、次のようにします(コードを理解するにはコメントを読んでください):
#include<stdio.h>
#include<string.h>
#define SIZE 50
void strrev(char* st) {// string reverse function()
char* f = st; // points to first
char* l = st + strlen(st) -1; // points to last char
char temp;
while(f < l){
// swap two chars in string at f & l memory
temp = *f;
*f = *l;
*l = temp;
f++;
l--;
}
}
int main(int argc, char* argv[]){
if(argc!=3) return 0;
FILE* input = fopen(argv[1],"r");
FILE* output = fopen(argv[2],"w");
int zipcode;
char population[SIZE] = {0};
while(fscanf(input,"%d %s\n",&zipcode, population)!= EOF){
// population is always alternative number
strrev(population); // reverse the string
//printf("%s\n",population);
fprintf(output,"%s ",population); // write in output file
}
return 1;
}
これは次のように機能します。
:~$ cat inputfile
46804 3450103 37215 1337 47906 46849
:~$ ./a.out inputfile outputfile
~$ cat outputfile
3010543 7331 94864
これは一種の単純な解決策です。
EDITコメントしているため、バイナリダンプファイルが必要です。したがって、バイナリ形式の出力ファイルが必要だと思います。出力ファイルをバイナリモードで開き、書き込み関数を使用するだけです。このために、私は部分的なコードを書いています(再びコメントを読んでください):
FILE* output = fopen(argv[2],"wb");
// ^ open in write binary mode
int val; // an extra variable int
while(fscanf(input,"%d %s\n",&zipcode, population)!= EOF){
strrev(population); // revers string
val = atoi(population); // convert strint to int
fwrite(&val,sizeof(int),1,output); // write in binary file
}