c - 在C中从文件到文件的读取和写入

标签 c scanf

我必须用 C 语言编写一个程序来从文件中读取数据并写入由代码创建的另一个文件。我按照老师的要求使用 Linux 的 Mac 终端(在 xCode 中编码)。所以我可以使用“gcc -o main2 main2.c”和“./main2”来编译它

输出是一团乱码,我疯狂地谷歌搜索,但找不到任何东西。我认为错误出在我的 Scanf 中,但我可能是错的。任何关于为什么这段代码不能正常工作的想法将不胜感激。谢谢。

#include <unistd.h>
#include <stdio.h>
#include "customer.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

int main()
{
    int fileid;
    int status;
    int matchcount;

    customer jdoe;

    fileid = open("Consumerman", O_WRONLY | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
//"%d %20c %d-%d-%d (%50c||<%d %40c>) %30c %2c %d %f"

    matchcount = scanf ("%d %20[^<>]c %d-%d-%d %50[^<>]c %20[^<>]c %2c %d %g",  &jdoe.idnumber, jdoe.name, &jdoe.year, &jdoe.month, &jdoe.day, /*&jdoe.address, jdoe.street,*/ jdoe.stringstreet, jdoe.city, jdoe.state, &jdoe.zipcode, &jdoe.points);


    while((matchcount != 0) && (matchcount != EOF)){
        status = write(fileid, (void *) &jdoe, sizeof(jdoe));

        matchcount = scanf (" %d %20[^<>]c %d-%d-%d %50[^<>]c %20[^<>]c %2c %d %g",  &jdoe.idnumber, jdoe.name, &jdoe.year, &jdoe.month, &jdoe.day, /*&jdoe.address, jdoe.street,*/ jdoe.stringstreet, jdoe.city, jdoe.state, &jdoe.zipcode, &jdoe.points);


    }
    close(fileid);
    return 0;
}

最佳答案

scanf() 对输入执行转换,而 write() 系统调用只是将原始数据转储到给定的文件描述符。您需要使用格式化函数(例如 printf())从(看起来的)数据结构获取纯文本输出,例如:

FILE* file = fopen("Consumerman", "w");
fprintf(file, "%d\n", jdoe.idnumber);
fclose(file);

PS:您首先使用系统调用有什么特殊原因吗?

关于c - 在C中从文件到文件的读取和写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21420679/

相关文章:

c - 为什么 strcmp 或 strncmp 不适用于 C 编程语言?

Windows 中区分大小写的目录路径

c - 替换数组中的数据时出现问题

c++ - 如何获得忘记算术运算的警告?

c - 使用一些 posix 命令的 C 程序

c - 如何通过指向结构中的松弛字节来访问另一个变量的数据?

c - 如何使用多线程丢弃 scanf 错误并从 4 个输入整数中识别最高素数

c - 从行 - C 读取多个整数

c - 如何在 C 中使用 scanf 扫描一个整数值后跟一个字符

C 结构不扫描所有输入