开发者

How to write into a file at particular path in linux using C

I want to write in file chunkcombined.playlist located at the path /var/streaming/playlists/chunkcombined/chunkcombined.playlist using C.

As the files (small chunks of video) get received through a socket, I want to add them automatically to a playlist.

For that I want to write the following lines in the file chunkcombined.playlist using C:

"/usr/local/movies//chunk0.mp4" 1
"/usr/local/movies//chunk1.mp4" 1
"/usr/local/movi开发者_如何学Pythones//chunk2.mp4" 1
"/usr/local/movies//chunk3.mp4" 5
"/usr/local/movies//chunk4.mp4" 5

How can I write into a file at particular path in Linux using C?


Use fopen() and fputs() functions.

Full example (with excessive comments):

#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;
}

This version retrieves the text line given as argument to the program and then writes it to desired file:

#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;
}

Example:

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

writes: "Hello, World!"

to:

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜