我需要比較stdin從fgets獲取的字符串與fscanf從文件獲取的另一個(並使用fprintf寫入文件)。我必須使用這兩個函數來從標準輸入和文件讀取。 我該怎麼做? ,因爲我已經看到fgets存儲「\ 0」字節,但是fscanf沒有。比較使用fgets和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;
}
哦,是的是的。 – 2012-09-05 19:05:48