为什么 fscanf 读数为 0?
Why is fscanf reading 0?
我正在制作一个可以逐行读取文件的简单程序。文件的每一行都采用以下格式:整数、整数、字符。例如,文件如下所示:
1 2 A
2 3 B
程序的预期输出应该是:
1 2 A
2 3 B
但是正在打印
0 2 A
0 3 B
我该如何解决?
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <stdint.h>
#include <time.h>
int main(int argc, char** argv) {
char const* const fileName = argv[1];
FILE* file = fopen(fileName, "r");
char str[1];
int key;
int val;
while (fscanf(file, "%d %d %s\n", &key, &val, str) != EOF) {
printf("Read Integer %d \n", key );
printf("Read Integer %d \n", val );
printf("Read String %s \n", str );
}
fclose(file);
return(0);
}
您将 str
声明为 char [1]
这是错误的。
您需要分配更大的 str
来容纳 '[=15=]'
。如下更改声明应该可以解决问题。
char str[2]; /* Or may be larger */
/* ^ */
此外,从 scanf
的格式字符串中删除 '\n'
也是一个好主意:
while (fscanf(file, "%d %d %s", &key, &val, str) == 3)
/* ^ ^^^^ */
您需要一个更大的字符串,您需要检查 argc
值,并且您需要更好的 fscanf()
格式。也最好检查 fscanf()
return 是 3.
#include <stdio.h>
#define N 500
#define XSTR(n) STR(n)
#define STR(n) #n
int main(int argc, char** argv)
{
if (argc < 2)
{
fprintf(stderr, "I need one argument.\n");
return 1;
}
char const* const fileName = argv[1];
FILE* file = fopen(fileName, "r");
char str[N + 1];
int key;
int val;
// "%d %d %" XSTR(N) "s" expands as "%d %d %500s"
while (fscanf(file, "%d %d %" XSTR(N) "s", &key, &val, str) == 3)
{
printf("Read Integer %d \n", key );
printf("Read Integer %d \n", val );
printf("Read String %s \n", str );
}
fclose(file);
return(0);
}
编辑:我添加了宏,以便在更改 N 时更新格式。
我正在制作一个可以逐行读取文件的简单程序。文件的每一行都采用以下格式:整数、整数、字符。例如,文件如下所示:
1 2 A
2 3 B
程序的预期输出应该是:
1 2 A
2 3 B
但是正在打印
0 2 A
0 3 B
我该如何解决?
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <stdint.h>
#include <time.h>
int main(int argc, char** argv) {
char const* const fileName = argv[1];
FILE* file = fopen(fileName, "r");
char str[1];
int key;
int val;
while (fscanf(file, "%d %d %s\n", &key, &val, str) != EOF) {
printf("Read Integer %d \n", key );
printf("Read Integer %d \n", val );
printf("Read String %s \n", str );
}
fclose(file);
return(0);
}
您将 str
声明为 char [1]
这是错误的。
您需要分配更大的 str
来容纳 '[=15=]'
。如下更改声明应该可以解决问题。
char str[2]; /* Or may be larger */
/* ^ */
此外,从 scanf
的格式字符串中删除 '\n'
也是一个好主意:
while (fscanf(file, "%d %d %s", &key, &val, str) == 3)
/* ^ ^^^^ */
您需要一个更大的字符串,您需要检查 argc
值,并且您需要更好的 fscanf()
格式。也最好检查 fscanf()
return 是 3.
#include <stdio.h>
#define N 500
#define XSTR(n) STR(n)
#define STR(n) #n
int main(int argc, char** argv)
{
if (argc < 2)
{
fprintf(stderr, "I need one argument.\n");
return 1;
}
char const* const fileName = argv[1];
FILE* file = fopen(fileName, "r");
char str[N + 1];
int key;
int val;
// "%d %d %" XSTR(N) "s" expands as "%d %d %500s"
while (fscanf(file, "%d %d %" XSTR(N) "s", &key, &val, str) == 3)
{
printf("Read Integer %d \n", key );
printf("Read Integer %d \n", val );
printf("Read String %s \n", str );
}
fclose(file);
return(0);
}
编辑:我添加了宏,以便在更改 N 时更新格式。