c - C语言从文件中读取数据

标签 c fopen fwrite file-management file-manipulation

所以我有一个包含数据的大文本文件,我想重新排列它。数据每行都有整数和 float 的组合,但我只对获取第一个整数(1 或 0)感兴趣,并将其放在行尾。

例如,在我的数据文件中,我有以下行
1 0.41 1 44
我想成为
0.41 1 44 1

这是我目前所拥有的,但无法使其正常工作。谢谢。

void main() {
FILE *fp;
FILE *out;

char str[15];
char temp;

fp = fopen("dust.txt", "r+");
out = fopen("dust.dat", "w");

while(fgets(str, sizeof(str), fp) != NULL) {
    temp = str[0];
    str[strlen(str)] = ' ';
    str[strlen(str)+1] = temp;
    str[strlen(str)+2] = '\r';
    str[strlen(str)+3] = '\n';

fwrite(str, 1, strlen(str), out);
}   

fclose(fp);
    fclose(out);
}

最佳答案

这将输出视为文本文件(与输入相同),而不是二进制文件。我在适当的地方放置了代码注释。您最严重的错误是在覆盖字符串终止符后调用 strlen。无论如何只需要调用一次。

#include <stdio.h>
#include <string.h>

int main(void)  {                           // main must be type int
    FILE *fp;
    FILE *out;
    char str[100];                          // be generous
    size_t len;

    fp = fopen("dust.txt", "r");
    out = fopen("dust2.txt", "w");          // text file
    if(fp == NULL || out == NULL)
        return 1;

    while(fgets(str, sizeof(str)-3, fp) != NULL) {
        str [ strcspn(str, "\r\n") ] = 0;   // remove trailing newline etc
        len = strlen(str);
        str[len] = ' ';                     // overwrites terminator
        str[len+1] = str[0];                // move digit from front
        str[len+2] = 0;                     // terminate string
        fprintf(out, "%s\n", str + 2);      // write as text
    }   

    fclose(fp);
    fclose(out);
    return 0;
}

输入文件:

1 0.41 1 44
0 1.23 2 555

输出文件:

0.41 1 44 1
1.23 2 555 0

关于c - C语言从文件中读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36777412/

相关文章:

C fwrite 输出在 Matlab 中显示不正确

php - 使用fwrite显示sql查询

c - 如何在C语言的二进制文件中插入\0

c - 如何将二维数组作为参数传递给 C 中的函数

c - 关于 FBX 二进制文件格式

c - 在 osx 上编译简单 C 程序时未找到 header 错误

c - 如何在c中缩放数字/数字范围

c - 如何 fopen() .IMA 文件?

c - 当我打开文件时会发生什么(RAM 和 ROM 很重要)

c - NULL 不初始化