【问题标题】:Check first six characters in csv file for a specific sequence检查 csv 文件中的前六个字符以获取特定序列
【发布时间】:2017-01-24 05:48:25
【问题描述】:

我正在尝试编写一个程序(显然是新的),它检查输入文件以确保它符合指定的格式。输入文件应该是 csv 格式,前两行分别以名称“Class”和“Subject”开头。 我知道在第二行开头检查“主题”指定会有点复杂,但我想我可以通过计算确定输入数据集的维度来找出从哪里开始读取/检查字符串逗号和换行符的数量。 但是,我对如何确保前六个字符是“Class”有点困惑。 我最初只是想弄清楚如何在前六个字符中扫描逗号(见下文),但我被困在那里。

    // search the first six characters for "Class,"
FILE *input;
    int character; 
    int comma_check = 0;
    int i = input[i];
    while (i < 6) 
    {
        character = fgetc(input);
        if (character == ',')
        {
            comma_check++;
        }
    }
    if (comma_check == 0)
    {
        printf("Input file is not in the correct format.\n");
        return 1;
        fclose(input);
    }

我已经阅读了许多建议如何打印到屏幕的帖子(尽管我还没有弄清楚如何只打印指定数量的字符而不是通过文件末尾),但我不知道'不知道如何将前六个字符保存到一个字符串中,然后我可以将其与“Class”进行比较。任何帮助或建议将不胜感激。提前谢谢!

编辑:感谢您的帮助。这就说得通了。同样,如果我想检查文件末尾是否有换行符或回车符,我可以这样做,对吧?

fseek(input, -2, SEEK_END);
char buf1[3] = {0};
if ((strncmp(buf1, "\n,", 2) == 0) || (strncmp(buf1, "\r,", 2) == 0))
{
    return 4;
    fclose(input);
}

这似乎合乎逻辑(\n 和 \r 各占 2 个字节,对),但它似乎不起作用。

【问题讨论】:

  • 你能用上述格式显示你的测试文件吗?

标签: c string file character


【解决方案1】:

使用fread 读取前6 个字符并与密钥进行比较。示例:

FILE *input;
int match = 0;
char buf[7] = { 0 };

input = fopen("variation_format_help.txt", "r");
if (!input)
{
    printf("error\n");
    return 0;
}

fread(buf, 1, 6, input);
if (strncmp(buf, "Class,", 6) == 0)
{
    match = 1;
    printf("%s match\n", buf);
}

此时您可以关闭文件或继续读取文件。如果要回到文件开头调用fseek(input, 0, 0);,就不用关闭文件再打开。

【讨论】:

  • 非常感谢您的帮助!
猜你喜欢
  • 2020-07-06
  • 2016-08-22
  • 1970-01-01
  • 1970-01-01
  • 2014-05-22
  • 1970-01-01
  • 1970-01-01
  • 2022-12-05
  • 1970-01-01
相关资源
最近更新 更多