C语言 如何在文本文件中添加新行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7195621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:29:02  来源:igfitidea点击:

How to add a new line in a text file?

c

提问by ken

I have a few lines of code:

我有几行代码:

strcat(myTxt,"data");
strcat(myTxt,"\n");
strcat(myTxt,"data1");

In between the lines I've done strcatof "\n"; however, when I do a write to a text file the "\n"is ignored and all the strings are concatenated as datadata1. How can I work around this issue?

在我所做strcat的两行之间"\n";但是,当我写入文本文件时,该文件将"\n"被忽略,所有字符串都连接为datadata1. 我该如何解决这个问题?

采纳答案by Daniel

For file output, you should do strcat of "\r\n"

对于文件输出,你应该做 strcat of "\r\n"

回答by Dacav

This code works for me:

这段代码对我有用:

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

int main ()
{
    char myTxt[100];

    myTxt[0] = 0;
    strcat(myTxt, "data");
    strcat(myTxt, "\n");
    strcat(myTxt, "data1");

    printf("%s\n", myTxt);
    return 0;
}

Did you initialize the buffer's first byte? Edit: works also with a file as output:

您是否初始化了缓冲区的第一个字节?编辑:也适用于文件作为输出:

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

int main ()
{
    char myTxt[100];
    FILE *out = fopen("out.txt", "wt");

    myTxt[0] = 0;
    strcat(myTxt, "data");
    strcat(myTxt, "\n");
    strcat(myTxt, "data1");

    fprintf(out, "%s\n", myTxt);
    fclose(out);
    return 0;
}