Tutorial Solutions 6: Arrays of Strings and Files

  1. What does this program print?

    What about when there are no command line arguments?

    #include <stdio.h>
    
    int
    main(int argc, char *argv[]) {
        printf("%s", argv[argc - 1]);
        return 0;
    }
    
    It prints the last command line argument.

    If there are no command line arguments it prints argv[0] which contains the program name.

  2. Write a C program last_argument_reversed.c which writes out its last command line argument with the characters in reverse order.

    Your program should print nothing if there are no command line arguments.

    For example:

    ./last_argument_reversed The quick brown fox
    xof
    
    #include <stdio.h>
    
    int
    main(int argc, char *argv[]) {
        int  i;
    
        if (argc > 1) {
            i = 0;
            while (argv[argc - 1][i] != '\0') {
                i = i + 1;
            }
            while (i > 0) {
                i = i - 1;
                printf("%c", argv[argc - 1][i]);
            }
            printf("\n");
        }
    
        return 0;
    }
    
  3. Write a function that searches for a given character in a given string and returns 1 if the string contains the character and 0 othewise. Your function should use the following prototype

    int inString(char c, char str[]);
    
    int inString(char c, char str[]){
        int i;
        for (i = 0; str[i] != '\0'; i = i + 1) {
            if (str[i] == c) {
                return 1;
            }
        }
        return 0;
    }
    
  4. Write a function with this prototype
    int notInLinesArray(char lines[N_LINES][MAX_LINE_LENGTH], int n, char string[])
    
    which returns 1 if string does not occur in the first n elements of array lines and 0 otherwise (hint use strcmp).
    
    int notInLinesArray(char lines[N_LINES][MAX_LINE_LENGTH], int n, char string[]) {
        int i;
        for (i = 0; i < n; i = i +  1) {
            if (strcmp(lines[i], string) == 0) {
                return 0;
            }
        }
        return 1;
    }
    
    
  5. Write a function with this prototype
    int hasDuplicates(char lines[N_LINES][MAX_LINE_LENGTH], int n);
    
    which returns 1 if no line occurs twice in the first n elements of array lines and 0 otherwise (hint use function from previous question).
    int hasDuplicates(char lines[N_LINES][MAX_LINE_LENGTH], int n, char string[]) {
        int i, j;
        for (i = 1; i < n; i = i +  1) {
            if (notInLinesArray(lines, i, char lines[i]) == 0) {
                return 0;
            }
        }
        return 1;
    }
    
  6. Write a function, matching the prototype below, that returns 1 if the strings s1 and s2 are the same and 0 if they are not.

    int same(char s1[], char s2[]);
    
    int same(char s1[], char s2[]) {
        int i = 0;
    
        while (s1[i] == s2[i] && s1[i] != '\0') {
            i = i + 1;
        }
    
       return s1[i] == s2[i];
    }
    
  7. Write a function, that mirrors the behaviour of the library function strncat. Your code should use the following prototype.

    void mystrncat(char string1[], char string2[], int n);
    

    Reminder: strncat appends string2 to string1, over writing the terminating null char ('\0') at the end of string1, and then adds a terminating null byte char. strncat will use at most n bytes from string2.

    void mystrncat(char string1[], char string2[], int n) {
        int i, len;
    
        // find the end of the first string
        for (len = 0; str1[len] != '\0'; len = len + 1) {
        }
    
        // start copying from the second string
        for (i = 0; i < n && str2[i] != '\0'; i = i + 1) {
            str1[len] = str2[i];
            len = len + 1;
        }
        str1[len] = '\0';
    }
    
  8. What do you use fopen for and with what parameters? If you want to read or write information to a file you need to use fopen to open the file first. You need to tell fopen the name of the file you wish to open and whether you want to open the file for reading ("r"), writing("w") or appending ("a"). Files that are opened for writing that already exist are truncated to size 0 (ie all contents are erased). So if you want to write information to a file but do not want to erase the current contents of the file you should use "a" append mode. If fopen is successful it returns a pointer to the file stream that has been opened, otherwise it returns NULL
  9. Under what circumstances would fopen return NULL? fopen returns NULL if the file you tried to open for reading does not exist. It will also return NULL if you try to open a file you do not have permission to access.
  10. Write C to read in the first line of a file named data.txt and display it on the screen.
    #include <stdio.h>
    #include <stdlib.h>
    
    #define MAX_LINE 1024
    
    int main(void){
        char line[MAX_LINE];
        FILE *stream
    
        stream = fopen("data.txt", "r");
        if (stream == NULL) {
            fprintf(stderr,"data.txt can't be opened for reading\n");
            return 1;
        }
        if (fgets(line, MAX_LINE, stream) != NULL) {
            printf("%s", line);
        }
        fclose(stream);  // uneeded
        return 0;
    }
    
  11. Write C to read in a string from a user and write it to a file called data.txt. If the file data.txt exists, it should be overwritten
    
    #include <stdio.h>
    #include <stdlib.h>
    
    #define MAX_LINE 1024
    
    int main(void){
        char line[MAX_LINE];
        FILE *stream
    
        stream = fopen("data.txt", "w");
        if (stream == NULL) {
            fprintf(stderr,"data.txt can't be opened for reading\n");
            return 1;
        }
        fgets(line, MAX_LINE, stdin);
        fprintf(stream, "%s", line);
        fclose(stream);
        return 0;
    }
    
    
  12. Write C to read in a string from a user and write it to a file called data.txt. If the file data.txt exists, it should append the line of text to the end of the file.
    #include <stdio.h>
    #include <stdlib.h>
    
    #define MAX_LINE 1024
    
    int main(void){
        char line[MAX_LINE];
        FILE *stream
    
        stream = fopen("blah.txt", "a");
        if (stream == NULL) {
            fprintf(stderr,"blah.txt can't be opened for reading\n");
            return 1;
        }
        fgets(line, MAX_LINE, stdin);
        fprintf(stream, "%s", line);
        fclose(stream);
        return 0;
    }
    
  13. Write a program that reads a set of integer numbers from a file and prints out the maximum number to standard output. The name of the input file should be specified as a command line argument.
    #include <stdio.h>
    #define FALSE 0
    #define TRUE 1
    
    int main(int argc, char * argv[]){
        FILE *fp;
        int num;
        int max;
        int maxAssigned = FALSE;
        if (argc < 2) {
            fprintf(stderr,"Incorrect Usage\n");
        } else {
            fp = fopen(argv[1], "r");
            if (fp == NULL) {
                fprintf(stderr,"Unable to open file %s\n",argv[1]);
            } else{
                while(fscanf(fp,"%d",&num) == 1){
                    if (maxAssigned == FALSE || num > max) {
                        maxAssigned = TRUE;
                        max = num;
                    }
               }
               fclose(fp);
            }
        }
        if (maxAssigned) {
            printf("Max : %d\n",max);
        }
        return 0;
    }