如何编写包含换行符的文本作为C中的命令行参数? [英] How to write text containing newline given as command line arguments in C?

查看:77
本文介绍了如何编写包含换行符的文本作为C中的命令行参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用C中的系统调用来创建具有多行内容的文本文件,并使用作为命令行参数提供的文本填充该文件.

I want to create a text file with mulitple lines using system calls in C and populate it with the text provided as command line arguments.

这是我写的:

#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

#define MAX_SZ 1024

int main(int argc, char *argv[]) {
    if (argc != 3) {
        printf("Invalid Number of arguments\n");
        printf("USAGE: ./a.out file_name \"msg\"\n");
    } else {
        int fd_creat, fd_open, fd_write;
        char file_name[MAX_SZ];
        char *msg = (char *)malloc(strlen(argv[2]) * sizeof(char));
        strcpy(file_name, argv[1]);
        fd_creat = creat(file_name, 0777);
        if (fd_creat < 2) {
            printf("ERROR: File could not be created\n");
        } else {
            fd_open = open(file_name, O_WRONLY);
            strcpy(msg, argv[2]);
            fd_write = write(fd_open, msg, strlen(msg));
            close(fd_open);
        }
    }
    return 0;
}

如果我以以下方式执行此程序:

If I execute this program as:

./a.out test.txt "Foo\nBar"

它将整个内容原样写入test.txt.基本上,我要在它们的单独行中加上"Foo"和"Bar".

It writes the whole thing into test.txt as it is. Basically, I want 'Foo' and 'Bar' in their separate lines.

推荐答案

这里有两个问题:

  • 您处理参数的方式并且未能为所涉及的数据分配足够的内存,
  • 正确解释诸如 \ n 之类的转义序列,因为shell会将它们原样地提供给您.
  • The way you're handling arguments and failing to allocate enough memory for the data involved,
  • Interpreting escape sequences like \n correctly since the shell will give them to you as-is, raw.
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

// This moves overlapping strings from src -> dest but only
// if dest is before src
void cc_str_drag(char* dest, char* src) {
    while (*dest) {
        *dest = *src;
        ++dest;
        ++src;
    }
}

// This interprets the \n sequence and can be extended to handle others, like
// \t, \\, or even \g.
void cc_interpret(char* str) {
    for (;*str; ++str) {
        // If this is a sequence start...
        if (*str == '\\') {
            // ...find out which one...
            switch (str[1]) {
                case 'n':
                    // Shift back...
                    cc_str_drag(str, &str[1]);
                    // ...and replace it.
                    *str = '\n';
                    break;
            }
        }
    }
}

int main(int argc, char *argv[]) {
    if (argc != 3) {
        printf("Invalid Number of arguments\n");

        // Remember argv[0] is the name of the program
        printf("USAGE: %s file_name \"msg\"\n", argv[0]);
        return -1;
    }

    // Since it's not the 1970s, use fopen() and FILE*
    FILE* output = fopen(argv[1], "w");

    if (!output) {
        printf("ERROR: File could not be created\n");
        return -2;
    }

    // Copying here to avoid tampering with argv
    char* str = strdup(argv[2]);

    // Replace any escape sequences
    cc_interpret(str);

    // Then just dump it directly into the file
    fwrite(str, 1, strlen(str), output);

    fclose(output);

    return 0;
}

请注意此处使用的工具:

Note the tools used here:

  • strdup 是一种比 malloc(strlen(slen))复制C字符串然后再复制的方法.那就是要求可怕的一对一错误.
  • FILE * 的性能要好得多,因为它已被缓冲. open()用于无法缓冲的低级操作.知道何时使用哪种工具.
  • 不要害怕编写处理字符串内容的函数.C字符串对于理解而不是恐惧非常重要.
  • strdup is a way quicker method of copying a C string than malloc(strlen(s)) and then copying it. That's asking for dreaded off-by-one errors.
  • FILE* performs much better because it's buffered. open() is used for low-level operations that can't be buffered. Know when to use which tool.
  • Don't be afraid to write functions that manipulate string contents. C strings are really important to understand, not fear.

这篇关于如何编写包含换行符的文本作为C中的命令行参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆