-1

我想从一个文件中获取 2 个固定长度的变量字符串(10chars 和 32chars),并将它们保存为变量,以便稍后在我的程序中传递并将它们写入一个新文件。我可以将数据从用户输入写入新文件,但我似乎不知道如何定位数据并将其存储以供使用,因此用户不必手动输入 42 个字符和风险错误。这些字符串的内容会有所不同,并且在文件中的位置可能会有所不同,但总是会出现在常量字符串“序列号 =”之后。如果有一个已知的刺痛开始的偏移位置怎么办,这可以使它更容易吗?我在想 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);
}

我整个周末都在工作和阅读,现在我得到了想要的结果,从一个文件中读取数据并注入到另一个文件中。虽然这可行,但它可能不是最好的方法。我提前为错误标记的帖子道歉,我从手机提交并且无法访问我的来源。感谢所有的投入。我更欢迎。当我了解自己在做什么时,我试图记录下来。

4

2 回答 2

0

您可以使用 fgetc 并计算一个字符串中的每个字符,并说如果 c==" " 表示另一个单词并重置您的计数。

于 2013-12-13T23:46:06.620 回答
0

尽管您的解决方案有效,但您可能会发现不必预先确定"test.txt"字符串开始位置的偏移量,而是让程序搜索它们,例如使用

#include <stdio.h>
#include <stdlib.h>

void find(FILE *f, const char *s)
{   // searches stream f for string s, positions f after s
    int c;
    long offset;
    const char *cp;
    for (; ; )
    for (offset = ftell(f), cp = s; ; ) // save starting point
        if (!*cp) return;   // at end of search string - found
        else
        if ((c = fgetc(f)) == *cp) ++cp;    // character match
        else
        if (c == EOF) printf("\"%s\" not found\n", s), exit(EXIT_FAILURE);
        else
        if (cp > s) { fseek(f, offset, SEEK_SET), fgetc(f); break; }
}

并更换

    fseek (f,443,SEEK_SET);  //file offset location to begin read

    fseek (f,501,SEEK_SET);  //file offset location to begin read

    find(f, "UUID =");          // really no space after "="?

    find(f, "Serial Number ="); // really no space after "="?

分别。

于 2016-11-07T09:33:37.237 回答