如何使用C在linux中的特定路径写入文件

时间:2011-04-21 14:41:20

标签: c linux

我想使用C在位于路径chunkcombined.playlist的文件/var/streaming/playlists/chunkcombined/chunkcombined.playlist中写入。

当通过套接字接收文件(小块视频)时,我想将它们自动添加到播放列表中。

为此,我想使用C:

在文件chunkcombined.playlist中编写以下行
"/usr/local/movies//chunk0.mp4" 1
"/usr/local/movies//chunk1.mp4" 1
"/usr/local/movies//chunk2.mp4" 1
"/usr/local/movies//chunk3.mp4" 5
"/usr/local/movies//chunk4.mp4" 5

如何使用C?

在Linux中的特定路径写入文件?

1 个答案:

答案 0 :(得分:2)

使用fopen()fputs()功能。

完整示例(评论过多):

#include <stdio.h>

int main(void)
{
    /* where to write */
    const char filepath[] =
        "/var/streaming/playlists/chunkcombined/chunkcombined.playlist";

    /* what to write */
    const char output_lines[] = 
        "\"/usr/local/movies//chunk0.mp4\" 1\n"
        "\"/usr/local/movies//chunk1.mp4\" 1\n"
        "\"/usr/local/movies//chunk2.mp4\" 1\n"
        "\"/usr/local/movies//chunk3.mp4\" 5\n"
        "\"/usr/local/movies//chunk4.mp4\" 5\n";

    /* define file handle */ 
    FILE *output;

    /* open the file */
    output = fopen(filepath, "wb");
    if(output == NULL) return -1; /* fopen failed */

    /* write the lines */
    fputs(output_lines, output);

    /* close the file */
    fclose(output);

    return 0;
}

此版本检索作为程序参数给出的文本行,然后将其写入所需文件:

#include <stdio.h>

int main(int argc, char *argv[])
{
    if(argv[1] == NULL) return -1; /* no arguments, bail out */

    /* where to write */
    const char filepath[] =
        "/var/streaming/playlists/chunkcombined/chunkcombined.playlist";

    /* define file handle */ 
    FILE *output;

    /* open the file */
    output = fopen(filepath, "wb"); /* change "wb" to "ab" for append mode */
    if(output == NULL) return -1; /* fopen failed */

    /* write the lines */
    fputs(argv[1], output);
    putc('\n', output);

    /* close the file */
    fclose(output);

    return 0;
}

示例:

./write "\"Hello, World!\""

写道:"Hello, World!"

为:

/var/streaming/playlists/chunkcombined/chunkcombined.playlist