从C中的文件读取-错误的输出

时间:2018-12-23 13:19:38

标签: c

我正在编写要从文件读取的代码,但是它总是输出错误的输出。

代码如下:

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);

结构为:

struct threeNum
{
    char n1, n2, n3;
};

.txt文件为:

1 2 3
5 6 7
6 6 9
5 5 5
8 7 2

我总是打印零。

2 个答案:

答案 0 :(得分:2)

@foreach( $permissions as $permission ) <tr> <th scope="row">{{ $permission -> id }}</th> <td>{{ $permission -> name }}</td> <td>{{ $permission -> created_at }}</td> <td>{{ $permission -> updated_at }}</td> <td><a href="{{ URL::to('/dashboard/users/assign-remove-permission/assign/' . $user_id . '/assign/' . $permission -> id) }}"> <span class="badge badge-success">Assign</span> </a> </td> </tr> @endforeach 读取二进制对象,但是您的文件是文本。您需要先阅读文本,然后进行解析(例如使用freadfscanf,后跟fgets)。

答案 1 :(得分:0)

// 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;
}