[英]Reading from file in C - Wrong output
I am writing a code to read from a file but it always prints wrong output.我正在编写代码以从文件中读取,但它总是打印出错误的输出。
The code is as follows:代码如下:
int n;
struct threeNum num = { 0 };
FILE *fptr;
if ((fptr = fopen("input.txt", "rb")) == NULL) {
printf("Error! opening file\n");
// Program exits if the file pointer returns NULL.
exit(1);
}
for (n = 1; n < 5; ++n)
{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3);
}
fclose(fptr);
The struct is:结构是:
struct threeNum
{
char n1, n2, n3;
};
And the.txt file is:而.txt文件是:
1 2 3
5 6 7
6 6 9
5 5 5
8 7 2
And I always get zeros printed.而且我总是打印零。
fread
reads binary objects, but your file is text. fread
读取二进制对象,但您的文件是文本。 You need to read text and then parse that (such as with fscanf
, or fgets
followed by sscanf
).您需要阅读文本然后对其进行解析(例如使用fscanf
或fgets
后跟sscanf
)。
// As @Arkku said, use fgets to read each line and sscanf to parse it.
#include <stdio.h>
#include <stdlib.h>
int main() {
int num[15];
int totalRead, i = 0;
char dataToRead[50];
FILE *fp;
if ((fp = fopen("file.txt", "r")) == NULL) {
printf("Error! opening file\n");
// Program exits if the file pointer returns NULL.
exit(1);
}
// read the file
while (fgets(dataToRead, 50, fp) != NULL) {
totalRead = sscanf(dataToRead, "%d%d%d", &num[i], &num[i+1], &num[i+2]);
puts(dataToRead);
i = i + 3;
}
// I used modulo so that after every 3rd element there is a newline
for (i = 0; i < 15; i++) {
printf("%d ", num[i]);
if ((i+1) % 3 == 0)
printf("\n");
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.