开发者

Replace line breaks with single space in C

I am not able to replace the line breaks in a file with a single space. Say for example the file contains

A book is a set or collection of written, printed, illustrated, or blank sheets, made of paper, parchment, or other various material.

Books may also refer to works of literature, or a main division of such a work. In library and information science, a book is called a monograph.

A store where books are bought and sold is a bookstore or bookshop. Books can also be borrowed from libraries.

There is a line break at the start of the sentence(A book is a set....) and again there is a line break before starting the next line(Books may also refer..)

I need this line break to replaced with a single space as follows

A book is a set or collection of written, printed, illustrated, or blank sheets, made of paper, parchment, or other various material, 开发者_Go百科usually fastened together to hinge at one side.Books may also refer to works of literature, or a main division of such a work. In library and information science, a book is called a monograph.A store where books are bought and sold is a bookstore or bookshop. Books can also be borrowed from libraries.

The contents will be in .csv file . At code level, I will be reading the file. So while reading the file using fgets how to hanle the line breaks. This is the way I would be reading the contents of the file.

int FileRead(char *inputfile)
{
    char buf[400]; 
    if ((fileinfo=fopen(inputfile,"r"))==NULL)


    /* read header row and ignore it */
    if (fgets(buf,400,fileinfo)!=NULL)
    {
        printf("read row");
        rowsread ++;
    }
    else
    {
        fclose(fileinfo);
        return;
    }

    while (fgets(buf,400,fileinfo)!=NULL)              /* read till EOF   */
    {
        rowsread ++;
        ............
        ............
        ............

Could anyone please help me out on this?


Just read the file one character at a time and test for '\n' - if the character is not equal to '\n' then output it unmodified, otherwise replace it by a space.


Depending on your operating system, the line breaks may be:
\r\n in MS Windows
\n in Linux
and \r in Mac as I remembered.


If your problem is to replace newlines with spaces, the usual approach in C is significantly easier. But I can't see how the problem as you specified integrates with CSV formatted files (a complete example would be wonderful) -- so this might only serve as a partial answer.

The general rule is: read in a character. Inspect it. Do something with it:

int c;
FILE *f;

while((c=getc(f)) != EOF) {
    if (c=='\n') {
        putchar(' ');
    } else {
        putchar(c);
    }
}

For each special case, you add another else if () block. (Or use a switch; all those break statements are distracting, though.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜