-4

Hi. I need to read several files without spaces or empty lines between characters.They can have different layouts, such as 1.txt, 2.txt or 3.txt:


1.txt:

t
h
i
s
f
i
l
e

2.txt:

l

i

k

e

t

h

a

t

3.txt:

s o m e t h i n g
l i k e 
t h a t

How do i do that ? I Just have the following code:

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

int main(){
    char c ;
    FILE *fp;

    fp = fopen("1.txt","r");
    if(fp == NULL){
    puts("Open file failed\n");
    exit(-1);
    }

    while(fscanf(fp,"%c\n",&c)!=EOF){
        /*do things with c var*/
    }

    fclose(fp);
    exit(0);
}
alk
  • 69,737
  • 10
  • 105
  • 255
santostiagoo
  • 1
  • 1
  • 2

1 Answers1

0

I think you're asking how to read in a text file, ignoring spaces and empty lines. Please clarify your question so that we can help you better.

Here's something to get you started:

You could read in the entire file, then remove anything you don't want. The following post agrees with my experience that your application will probably run faster that way: Reading a file faster in C

If you agree with that approach, this next post will show you how to read the text file into a buffer, with some error handling: Reading the whole text file into a char array in C

Then you can use something like this to remove the spaces, and something similar for the extra new lines: Function to remove spaces from string/char array in C

I hope this helps get you started, and perhaps someone will find time today to post some code for you.

Community
  • 1
  • 1
Madmartigan
  • 143
  • 1
  • 7
  • This question is solved. With a single char it works... Now, another question, similar to this but with words...if I have words instead of characters and I just have one word in a line? That is, words without empty lines between them. Question link: [link](http://stackoverflow.com/questions/23498148/read-words-from-file-without-empty-lines-in-c) – santostiagoo May 06 '14 at 15:10