【问题标题】:Write to .txt file?写入 .txt 文件?
【发布时间】:2012-07-19 09:54:35
【问题描述】:

如何将一小段文本写入.txt 文件? 我已经在谷歌上搜索了 3-4 多个小时,但不知道该怎么做。

fwrite();参数太多,不知道怎么用。

当您只想将名称和几个数字写入.txt 文件时,最容易使用的函数是什么?

char name;
int  number;
FILE *f;
f = fopen("contacts.pcl", "a");

printf("\nNew contact name: ");
scanf("%s", &name);
printf("New contact number: ");
scanf("%i", &number);

fprintf(f, "%c\n[ %d ]\n\n", name, number);
fclose(f);

【问题讨论】:

  • @user1054396:问题不在于打印(你没看错),而在于通过scanf 阅读。如果你读到%s,你必须读入一个足够长的缓冲区,而不是单个字符。
  • "fwrite() 有这么多的论点'" 摆脱它。它有四个

标签: c linux


【解决方案1】:
FILE *f = fopen("file.txt", "w");
if (f == NULL)
{
    printf("Error opening file!\n");
    exit(1);
}

/* print some text */
const char *text = "Write this to the file";
fprintf(f, "Some text: %s\n", text);

/* print integers and floats */
int i = 1;
float pi= 3.1415927;
fprintf(f, "Integer: %d, float: %f\n", i, pi);

/* printing single chatacters */
char c = 'A';
fprintf(f, "A character: %c\n", c);

fclose(f);

【讨论】:

  • 你知道你把 π 写成 pi 而不是 py 吗?
【解决方案2】:
FILE *fp;
char* str = "string";
int x = 10;

fp=fopen("test.txt", "w");
if(fp == NULL)
    exit(-1);
fprintf(fp, "This is a string which is written to a file\n");
fprintf(fp, "The string has %d words and keyword %s\n", x, str);
fclose(fp);

【讨论】:

    【解决方案3】:

    嗯,你需要先买一本关于 C 的好书并理解这门语言。

    FILE *fp;
    fp = fopen("c:\\test.txt", "wb");
    if(fp == null)
       return;
    char x[10]="ABCDEFGHIJ";
    fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);
    fclose(fp);
    

    【讨论】:

    • 与使用 fprintf()fputs() 相比,这是一项艰苦的工作。尤其是fprintf(),因为也必须写一些数字。
    • "c:\\test.txt" 是一个不太可能的文件名;问题被标记为linux
    • -1 OP 要求使用最简单的函数。并写入文本,但您以二进制模式打开文件。不报告打开错误是一种糟糕的做法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-03
    • 2012-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多