C语言 向字符串添加行结束符

yhuiod9q  于 2023-03-22  发布在  其他
关注(0)|答案(2)|浏览(180)

我收到一些参数,我转换成char和连接创建一个字符串,写入一个.txt文件。我试图添加一个0在上述字符串的末尾作为行结束符。然而,当我在我的ubuntu终端上使用file 10.txt,我得到10.txt: ASCII text, with no line terminators
要添加行结束符,需要更改什么?

int main() {
    int res;
    res = set_value(10, "abc", 3, 2.0);
}

int set_value(int key, char *value1, int value2, double value3) {
    char name[1000];
    int status;
    char line[5000];
    char temp[1000];
    int n;

    // Change directory where we work.
    if (chdir("FilesPractice1") == -1) {
        perror("Error while changing directories.");
        return -1;
    }

    // Convert key to the name of the file.
    snprintf(name, 1000, "%d.txt", key);

    // Open the file.
    if ((status = open(name, O_RDONLY)) == -1) {
        // Since the file doesnt exist, we proceed to create it.
        if ((status = open(name, O_WRONLY | O_CREAT, 0666)) == -1) {
            perror("Error while creating the tuple.\n");
            return -1;
        }
        // Format the key and values to write them into the file.
        snprintf(line, 5000, "%d, ", key);
        
        n = strlen(value1);
        strncat(line, value1, n);
        
        snprintf(temp, 1000, ", %d, ", value2);
        n = strlen(temp);
        strncat(line, temp, n);
        
        snprintf(temp, 1000, "%f", value3);
        n = strlen(temp);
        strncat(line, temp, n);
        
        n = strlen(line);
        line[n + 1] = 0;

        // Write the values into the file.
        write(status, line, strlen(line));

    } else {
        // Since file already exists, it is considered an error.
        perror("Error: key value already exists.\n");
        return -1;
    }

    // Close the file.
    if (close(status) == -1) {
        perror("Error while closing the file.");
        return -1;
    }

    return 0;
}
axr492tv

axr492tv1#

为了向字符串追加一个换行符,只需使用strcat(line, "\n");
还要注意这些备注:

  • 调用strncat(line, temp, strlen(temp))完全等同于strcat(line, temp)
  • 如果文件已经存在,则忘记关闭该文件。
  • 应该在main函数之前定义或至少声明set_value函数。

没有理由在你的代码中使用单独的snprintf调用,你可以简单地写:

snprintf(line, sizeof line, "%d, %s, %d, %f\n",
             key, value1, value2, value3);

如果出于某种原因必须一次构造一个字段的输出行,可以通过跟踪输出行中的位置来简化代码,而不是为片段使用单独的数组并使用strcat连接它们:

#include <stdio.h>

int set_value(int key, char *value1, int value2, double value3) {
    char filename[32];
    int status;
    char line[5000];

    // Change directory where we work.
    if (chdir("FilesPractice1") == -1) {
        perror("Error while changing directories.");
        return -1;
    }

    // Convert key to the name of the file.
    snprintf(filename, sizeof filename, "%d.txt", key);

    // Open the file.
    if ((status = open(filename, O_RDONLY)) != -1) {
        // The file already exists, close it and report the error
        close(status);
        // Cannot use `perror` as `errno` was not set
        fprintf(stderr, "Error: key value file %s already exists.\n", filename);
        return -1;
    }

    // Since the file doesn't exist, we proceed to create it.
    if ((status = open(name, O_WRONLY | O_CREAT, 0666)) == -1) {
        perror("Error while creating the tuple.\n");
        return -1;
    }
    // Format the key and values to write them into the file.
#if 0
    // Single call to snprintf
    size_t pos = snprintf(line, sizeof line, "%d, %s, %d, %f\n",
                          key, value1, value2, value3);
#else
    // Separate calls for different parts
    size_t pos = snprintf(line + pos, sizeof line - pos, "%d", key);
    if (pos < sizeof line)
        pos += snprintf(line + pos, sizeof line - pos, ", %s", value1);
    if (pos < sizeof line)
        pos += snprintf(line + pos, sizeof line - pos, ", %d", value2);
    if (pos < sizeof line)
        pos += snprintf(line + pos, sizeof line - pos, ", %f", value3);
    if (pos < sizeof line)
        pos += snprintf(line + pos, sizeof line - pos, "\n");
#endif
    // Check if line is long enough.
    if (pos >= sizeof line) {
        fprintf(stderr, "Buffer size too small: need %zu bytes\n", pos + 1);
    }
    // Write the values into the file.
    ssize_t len = strlen(line);
    ssize_t nwritten = write(status, line, len);
    if (nwritten != len) {
        fprintf(stderr, "Error writing to %s: %zd bytes written, expected %zd.\n",
                filename, nwritten, len);
    }

    // Close the file.
    if (close(status) == -1) {
        perror("Error while closing the file.");
        return -1;
    }

    return 0;
}

int main(void) {
    int res;
    res = set_value(10, "abc", 3, 2.0);
}
0aydgbwb

0aydgbwb2#

“ASCII文本,无行终止符”表示文件末尾没有line ending(CR或LF)。
这不是一个错误,它只是描述了文件的内容。
如果你想像上面说的那样添加行终止符,而不是:

...
n = strlen(line);
line[n + 1] = 0;
...

将这两行更改为下面的LF(Linux约定)行:

strcat(line, "\n");

或者,如果您同时需要CR和LF(Windows约定):

strcat(line, "\r\n");

编辑:将strncat更改为strcat

相关问题