繁体   English   中英

比较使用fgets和fscanf获取的字符串

[英]compare string acquired with fgets and fscanf

我需要比较一个由fdin从stdin获取的字符串,以及另一个由fscanf从文件中获取的字符串(并使用fprintf写入文件)。 我必须使用这两个函数从stdin和文件中读取。 我怎么能这样做? 因为我看到fgets也存储“\\ 0”字节,但是fscanf没有。

这是代码:

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

typedef struct asd {
    char a[20];
    char b[20];
} struttura;


void stampa_file() {
struttura *tmp = NULL;
struttura *letto = NULL;
FILE *file;

tmp = (struttura *)malloc(sizeof(struttura));
letto = (struttura *)malloc(sizeof(struttura));
file = fopen("nuovoFile", "r");
printf("compare:\n");\
fgets(letto->a, sizeof(letto->a), stdin);
fgets(letto->b, sizeof(letto->b), stdin);
while(!feof(file)) {
    fscanf(file, "%s %s\n", tmp->a, tmp->b);
    printf("a: %s, b: %s\n", tmp->a, tmp->b);
    if(strcmp(letto->a, tmp->a) == 0 && strcmp(letto->b, tmp->b)) {
        printf("find matching\n");
    }
}
free(tmp);
free(letto);
}

int main() {
struttura *s = NULL;
FILE *file;

s = (struttura *)malloc(sizeof(struttura));

file = fopen("nuovoFile", "a+");
printf("");
fgets(s->a, sizeof(s->a), stdin);
printf("");
fgets(s->b, sizeof(s->b), stdin);
fprintf(file, "%s%s\n", s->a, s->b);
fclose(file);
stampa_file();

free(s);
return 0;
}

这里有很多潜在的问题,取决于你想要做什么

  • fgets读取一行(直到并包括换行符),而fscanf(.."%s"..)读取由空格分隔的标记。 完全没有相同的东西。

  • fscanf(.."%s"..)不检查您要写入的缓冲区的边界。 你真的想要fscanf(.."%19s"..)来确保它不会向你的20字节缓冲区写入超过20个字节(包括NUL终结符)。

  • while(!feof(fp))几乎总是错的。 feof没有告诉你,如果你在文件的末尾,它会告诉你是否已经尝试读取文件的末尾。 因此,如果您只是读到文件的末尾并且尚未读过它,则feof将返回false,但下一次读取将失败。

  • 你真的想检查fscanf的返回值,以确保它读取你想要读取的内容(并实际上向输出缓冲区写了一些内容。)结合上面的内容,这意味着你可能希望你的循环类似于:

     while (fscanf(fp, "%19s%19s", tmp->a, tmp->b) == 2) { : 

我怎么能这样做? 因为我看到fgets也存储“\\ 0”字节,但是fscanf没有。

我刚刚阅读了fscanf的文档并测试了它,这很好用:

#include <stdio.h>

int main()
{
    char str[100] = { 1 }; // intentionally initialized to nonzero junk
    fscanf(stdin, "%s", str);
    if (strcmp(str, "H2CO3") == 0)
        printf("This is me\n");
    else
        printf("This is not me\n");
    return 0;
}

使用%s传递时,scanf或fscanf会终止换行符或空格字符串上的字符串。 fgets一直等到\\ n。

因此,如果你打电话

fscanf(stdin, "%s", str);

vs

fgets(str);

并且文件包含“Hello there”

fscanf只包含“Hello”,其中fgets将返回整个字符串

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM