Namespace LogoNamespace0.3L
cs140pythoncs141csswebdevhtmlalgorithmsmathethics

  Guide

CS241 (OC & CN) Labs

Fri May 19 2023
Lab 1

Ex1. Complete the program by writing the code for the function count_words that takes a string as input and returns the number of words in the string.

  c  
#include<stdio.h>
#include<string.h>

int count_words(char *str){

    // this function should return the number of words in str
    char * sep = " ";
    char * token = strtok(str, sep);
    int sum = 0;

    while(token != null) {
      sum++;
      token = strtok(null, sep);
    }

    return sum;
}

int main(){
    char str[100];

    printf("Enter a string:");

    // this function reads a line or at most 99 bytes from stdin file
    // stream that represents the keyboard
    fgets(str,100,stdin);
    printf("Number of words in the entered string is %d\n",
                                %count_words(str));

    return 0;
}

Ex2. Write a C program that copies the content of one text file into another. You should write two versions of the program; one using file streams only and another using file descriptors only.

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

#define BUFSIZE 1024

int cpy_strm(char * dst, char * src) {
  FILE * srcf = fopen(src, "r");
  FILE * dstf = fopen(dst, "w");

  if (srcf == NULL || dstf == NULL)
    return 1; // Exit unsuccessfully

  char buf[BUFSIZE];

  while(fgets(buf, BUFSIZE, srcf) != NULL)
    fprintf(dstf, "%s", buf);

  fclose(srcf);
  fclose(dstf);

  return 0;
}

int cpy_desc(char * dst, char * src) {
    int srcd = open(src, O_RDONLY | O_CREAT, 0644);
    int dstd = open(dst, O_WRONLY | O_CREAT, 0644);

    if (srcd < 0 || dstd < 0)
      return 1;

    int n;
    char buf[BUFSIZE];

    while((n = read(srcd, buf, BUFSIZE-1)) > 0) {
      buf[n] = '\0';
      write(dstd, buf, n + 1);
    }

    close(srcd);
    close(dstd);
    return 0;
}

int main() {
  int res;

  // res = cpy_strm("out.txt", "in.txt");
  res = cpy_desc("out.txt", "in.txt");

  if (res != 0) printf("Error: could not open in.txt and/or out.txt\n");
  else printf("Success: copied files\n");
}