Thread: getline and copy funcitons

  1. #1
    Registered User
    Join Date
    Mar 2011
    Posts
    5

    getline and copy funcitons

    Can someone explain me getline() and copy() ? I've tried to read and read it again but I can't understand it.

    This is a code from "The C Programming Language, Kernighan and Ritchie"

    Code:
    #include <stdio.h>
    #define MAXLINE 1000 /* maximum input line lenght */
    
    
    int getline(char line[], int maxline);
    void copy(char to[], char from[]);
    
    /* print the longest input line */
    main()
    {
    	int len;		/* current line lenght */
    	int max;		/* maximum lenght seen so far */
    	char line[MAXLINE];	/* current input line */
    	char longest[MAXLINE]; 	/* longest line saved here */
    
    	max = 0;
    	while ((len = getline(line, MAXLINE)) > 0)
    		if (len > max) {
    		max = len;
    	copy(longest, line);
    }
    	if (max > 0) /* there was a line */
    	printf("%s", longest);
    	return 0;
    }
    
    /* getline: read a line into s, return lenght */
    	int getline(char s[],int lim)
    {
    	int c, i;
    	for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
    		s[i] = c;
    		if (c == '\n') {
    		s[i] = c;
    		++i;
    }
    	s[i] = '\0';
    	return i;
    }
    
    /* copy: copy 'from' into 'to'; assume to is big enough */
    	void copy(char to[], char from[])
    {
    	int i;
    	i = 0;
    	while ((to[i] = from[i]) != '\0')
    	++i;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    34,310
    > Can someone explain me getline() and copy() ?
    You mean the comments aren't a big enough clue?

    /* getline: read a line into s, return lenght */
    /* copy: copy 'from' into 'to'; assume to is big enough */

    Perhaps you should try to post what you think they do, and what bits of your explanation concern you as being weak/wrong.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. linking error
    By DavidP in forum C++ Programming
    Replies: 3
    Last Post: 05-22-2007, 12:24 AM