c - 从 C 文件中读取字符串和整数的组合

标签 c stdio file-read

我是C语言的新手,所以请多多包涵。我试图读取一个包含字符串的文件,但获得的输出是单个字符。

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

#define CALLOC(num, type) ((char*)calloc (num, sizeof(char)))
#define FREE(addr) (free((void*) (addr)))

int i, count;
char *x, *y, *z;

int main (void) 

{

FILE *stream;
if ( (stream = fopen ( "test.txt", "r" )) == NULL )
{ printf ("Cannot read the new file\n");
exit (1);
}

count = 3;

x=CALLOC(count, char);
y=CALLOC(count, char);
z=CALLOC(count, char);


for ( i=0; i<count; i++ ) 
{ fscanf (stream,"%c %c %c", &x[i], &y[i], &z[i]);
printf ("\n %d %c %c %c ", i, x[i], y[i], z[i]);
}

FREE(x);
FREE(y);
FREE(z);

fclose (stream);

}

输入的test.txt文件包含

1 ab 1
2 aa 5
1 cc 1

电流输出

 0 1 a b
 1   1 2
 2   a a 

预期输出

 0 1 ab 1
 1 2 aa 5
 2 1 cc 1

我怀疑我是否应该使用字符数组,但它似乎不起作用,我觉得使用 char 读取 int 是可以接受的。在这里我需要预期的输出,为此任何方法/建议都是值得赞赏的。

最佳答案

%c 只读取一个字符。所以它不会将 ab 读取为单个字符。您在文件中的行和您的格式无法正确读取整行。

一个简单的方法是使用 fgets() 并打印整行:

char line[256];
i = 0;

while(fgets(line, sizeof line, stream))
{
   printf ("%d %s", i, line);
   i++;
}

顺便说一下,callocfree 的宏是不必要的。与直接使用这些函数相比,它们并没有使代码更易于阅读。

还有 casts in them are also unnecessary .

关于c - 从 C 文件中读取字符串和整数的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31536689/

相关文章:

c - exit 命令在我自己的 shell 中不能正常工作

java - 如何使用Android接收特定 radio 频率

c - putc 需要标准输出,vs puts

python - 在python中读取一个pgm文件

android - 在不使用资源的情况下将外部文本文件加载到 Android 应用程序中

python - int 到字符串连接

c - 重定向标准输入

c - fmemopen 给出 Valgrind 错误

c - 即使添加了 #include <stdio.h> 也隐式声明了 popen

python多处理读取文件花费太多时间