LinuxQuestions.org
Help answer threads with 0 replies.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 12-11-2009, 07:40 PM   #1
gerard4143
LQ Newbie
 
Registered: Jan 2008
Location: P.E.I. Canada
Posts: 18

Rep: Reputation: 1
C Truncating Strings


I wrote this small program that will truncate a string that's entered in by the user.
An example of its usage:

if the user enters in a string say "abcdefghijklmnopqrstuvwxyz" the program will only take the first 9 characters and truncate the rest so that the user can be prompted for a second string and not be worried about remaining characters left in the stream.

Now this program works O.K. but I would like to find something in C that has this functionality build into it...Does anyone know of any function that will accomplish this...

Code:
#include <stdio.h>
#include <stdlib.h>

#define BSIZE 10

void getstring(char *s, FILE *fd, int size)
{
    int i = 0;

    while ((s[i++] = fgetc(fd)) != '\n')
    {
        if (i > size) --i;
    }

    s[--i] = '\0';    
}

int main(int argc, char**argv)
{
    char testch1[BSIZE];
    char testch2[BSIZE];

    fputs("enter a test string~>", stdout);
    getstring(testch1, stdin, (BSIZE - 1));
    fprintf(stdout, "string~>%s\n", testch1);    

    fputs("enter a test string~>", stdout);
    getstring(testch2, stdin, (BSIZE - 1));
    fprintf(stdout, "string~>%s\n", testch2);    


    exit(EXIT_SUCCESS);
}
 
Old 12-11-2009, 07:49 PM   #2
gerardorn
LQ Newbie
 
Registered: Nov 2009
Location: México
Posts: 9

Rep: Reputation: 0
what bout the strncpy function?
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Truncating a file in linux bobbera Linux - Software 2 09-09-2008 07:51 AM
Truncating Script blu_alchemist Linux - Software 4 09-13-2007 06:40 PM
how to find duplicate strings in vertical column of strings markhod Programming 7 11-02-2005 04:04 AM
Truncating trailing characters liguorir Programming 0 05-23-2004 04:00 AM
Truncating a string nkendrick Linux - General 5 11-29-2003 09:12 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 09:35 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration