我想从文件中获取 2 个固定长度的变量字符串(10 个字符和 32 个字符),并将它们保存为变量,以便稍后在我的程序中传递,并将它们写入新文件。我可以根据用户输入将数据写入新文件,但我似乎不知道如何找到数据并将其存储以供使用,这样用户就不必手动输入 42 个字符并冒着错误的风险。这些字符串的内容会有所不同,并且在文件中的位置也可能会有所不同,但始终位于常量字符串“Serial Number =”之后。如果有一个已知的蜇伤开始的偏移位置怎么办,这可以让事情变得更容易吗?我在想 fget 或 fread...但我找不到一个有效的例子。
#include <stdio.h>
#include <string.h>
int main(void)
{
FILE *f;
FILE * pFile;
char sn[11];
char uuid[33];
if (f = fopen("test.txt", "rt"))
{
fseek (f,443,SEEK_SET); //file offset location to begin read
fread(uuid, 1, 32, f); //Read the data of 32 chars
uuid[32] = 0;
fseek (f,501,SEEK_SET); //file offset location to begin read
fread(sn, 1, 10, f); //Read the data of 10 chars
sn[10] = 0;
fclose(f); //Close our file
printf("The 32 character UUID:\n%s\n", uuid); //Show read/extracted Data
printf("The 10 character SN:\n%s\n", sn); //Show read/extracted Data
pFile = fopen ("testfile.exe","r+b"); //Open binary file to inject data
fseek (pFile,24523,SEEK_SET); //1st file offset location to begin write
fputs (sn,pFile); //Write our data!
fseek (pFile,24582,SEEK_SET); //2nd file offset location to begin write
fputs (uuid,pFile); //Write our data!
fseek (pFile,24889,SEEK_SET); //3rd file offset location to begin write
fputs (uuid,pFile); //Write our data!
fclose(pFile); //Close our file
printf ("Finished\n");
}
return(0);
}
我整个周末都在工作和阅读它,现在我得到了想要的结果,从一个文件读取数据并注入(inject)到另一个文件中。虽然这有效,但可能不是最好的方法。我提前为错误标记的帖子道歉,我是通过手机提交的,并且无法访问我的来源。感谢所有的投入。我欢迎更多。我尝试记录我所理解的自己在做什么。
最佳答案
您可以使用 fgetc 计算一个字符串中的每个字符,并判断 c==""是否表示另一个单词并重置您的计数。
关于C 从文件中获取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20577835/