skipping \n when reading from file

This is a discussion on skipping \n when reading from file within the C Programming forums, part of the General Programming Boards category; How can I skip new lines when reading from file? Here is the source code... Code: int view_all_fields() { FILE ...

  1. #1
    Registered User
    Join Date
    Aug 2003
    Posts
    11

    skipping \n when reading from file

    How can I skip new lines when reading from file?
    Here is the source code...


    Code:
    int view_all_fields()
    {
    
    	FILE *fp = fopen ( "db.txt", "r" );
    	char buff[BUFSIZ];
    
    	if ( fp == NULL ) {
    
    		perror("view_all_fields -- fopen");
    		return 0;
    
    	}
    	
    	else {
    
    		while ( fgets(buff, sizeof buff, fp) != NULL ) {
    
    			printf("%s", buff);
    
    		}
    
    	}
    
    }

    in file db.txt there is smthing like that...

    text

    text1

    text2

    text3

    I want to remove the new lines when displaying

  2. #2
    Registered User
    Join Date
    Aug 2003
    Posts
    11
    that's a different thing
    thank you!

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    I take it you want to remove the newline from buff left by fgets?
    Code:
    char *newline;
    if ((newline = strchr(buff, '\n')) != NULL)
        *newline = '\0';
    My best code is written with the delete key.

  4. #4
    Registered User char's Avatar
    Join Date
    Apr 2002
    Posts
    31
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define PATH "/usr/home/text"
    
    int main(void)
    {
        char buf[BUFSIZ];
        FILE *fp;
    
        if ((fp = fopen(PATH, "r")) == NULL)
    	    perror("fopen"), exit(EXIT_FAILURE);
    
        while (fgets(buf, BUFSIZ, fp))
        {
    	if (*buf == '\n')
    	    continue;
    	fputs(buf, stdout);
        }
    
        fclose(fp);
    
        return EXIT_SUCCESS;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. sequential file program
    By needhelpbad in forum C Programming
    Replies: 80
    Last Post: 06-08-2008, 01:04 PM
  3. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 04:02 AM
  4. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 01:53 AM
  5. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21