我想知道如何让这段代码将文本文件从文本值覆盖为 ASCII 值。
我希望它做这样的事情:
CMD > c:\users\用户名\桌面>cA5.exe content.txt
content.txt 中有“abc”,我希望命令行将“abc”更改为其 ASCII 值。 97...等等。我不想在命令窗口中写入任何内容,我希望它在文本文件中进行更改。这可能吗?如果可以,我该如何使用现有代码来做到这一点?
#include <stdio.h>
#include <stdlib.h>
int main(int argc[1], char *argv[1])
{
FILE *fp; // declaring variable
fp = fopen(argv[1], "rb");
if (fp != NULL) // checks the return value from fopen
{
int i;
do
{
i = fgetc(fp); // scans the file
printf("%c",i);
printf(" ");
}
while(i!=-1);
fclose(fp);
}
else
{
printf("Error.\n");
}
}
最佳答案
不是最好的代码,但非常简单。
#include <stdio.h>
#include <stdlib.h>
void convertToAHex(char *data, long int size, FILE *file){
rewind(file);
int i;
for(i = 0; i < size; ++i){
fprintf(file, "%d ", data[i]);
}
}
int main(int argc, char *argv[]){
if(argc != 2){
return EXIT_FAILURE;
}
FILE *file = fopen(argv[1], "r+");
if(file){
char *data;
long int size;
fseek(file, 0, SEEK_END);
size = ftell(file);
rewind(file);
data = (char *) calloc(size, sizeof(char));
if(data){
fread(data, 1, size, file);
convertToAHex(data, size, file);
free(data);
}
fclose(file);
}
return EXIT_SUCCESS;
}
关于c - 通过 CMD 窗口和 C exe 写入文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13735190/