dannycrief
dannycrief

Reputation: 91

Open file in vi/vim using C language

Hello! I'm new in C language, so sorry for that. My program must create a new text editor instance (e.g. vi) - and open in it a file whose name the user will give as the argument to call the program. If the user does not provide a file name to open, an "empty" notebook should be opened.

I've already done with opening vi editor in C. And all I need to know is it possible to open a file in vi or vim using C language?

There is my code

#include <stdio.h>
#include <unistd.h>

int main (int argc, char *argv[]) {

    FILE *fp;
    int childpid;
    int count1 = 0, count2 = 0;

    fp = fopen(argv[1], "a");

    if(fp == NULL) {
        char *exe_name = "vi", *message = "Empty notebook is running.";
        char *exe_args[] = { exe_name, message, argv[0], NULL };
        execv("/usr/bin/vi", exe_args);
    }

    printf("Before it forks");

    sleep(5);

    childpid = fork();

    if(childpid == 0) {
        printf("This is a child process\n");
        while(count1 < 10) {
            printf("Child Process: %d\n", count1);
            sleep(1);
            count1++;
        } 
    } else {
        printf("This is the parent process\n");
        while(count2 < 20) {
            printf("Parent Process: %d\n", count2);
            sleep(1);
            count2++;
        } 
    }
    fclose(fp);
    return 0;
}

Thank you a lot!

Upvotes: 0

Views: 1753

Answers (1)

ice05
ice05

Reputation: 529

Yes you definitely can! I would, however, check over how you are opening the "empty" notebook in the first place. Your exec_args[] contains the following:

["vi", "Empty notebook is running.", argv[0], "\0"]

argv[0] is the name of your C executable, so lets assume it is a.out. So, when execv() gets called, you are essentially running the following command:

/usr/bin/vi Empty\ notebook\ is\ running a.out 

You are opening two files for editing, a file called "Empty notebook is running." (Note the slashes to escape the spaces in the command above), and the C executable that you made. I do not think you intend on opening both of those, since you usually should not mess with the actual executable file. Additionally, once you make changes to the "Empty notebook is running." file, the next time the program is run, you will see those changes!

So, I suggest you do not pass a file name at all. That way, vi opens up as if the user themselves never passed in a file name.

To open an existing file (and nothing else), you can simply add and else clause to your check of the file descriptor. So, the code can look something like:

if(fp == NULL)
{
    char *exec_args[] = {"vi", NULL};
    execv("/usr/bin/vi", exec_args);
}
else
{
    char *exec_args[] = {"vi", argv[1], NULL};
    execv("/usr/bin/vi", exec_args);
}


Upvotes: 2

Related Questions