Read text file in Xcode (.rtf)

Discussion in 'Mac Programming' started by tombaxterlfc, Feb 27, 2018.

  1. tombaxterlfc macrumors newbie

    Joined:
    Feb 27, 2018
    #1
    This below is an example code which opens a text file and then prints it out. Inside the text file is "Hello". The output gives "hello" but loads of random characters before this:


    #include <stdio.h>

    #include <stdlib.h>


    int main(void)

    {

    FILE *pFile; // pointer to file

    char ch;



    // Open text file in read mode

    pFile = fopen("text.rtf","r");



    // Check if fopen() was succesful

    if(pFile == NULL)

    {

    // File opening fail

    printf("Cannot open file\n");

    exit(1);

    }



    // File opened successfully, read until end of file

    while((ch = getc(pFile)) != EOF)

    {

    putchar(ch);

    }



    // Close file

    fclose(pFile);







    }

    This has gave the output.

    {\rtf1\ansi\ansicpg1252\cocoartf1404\cocoasubrtf470

    {\fonttbl\f0\fswiss\fcharset0 Helvetica;}

    {\colortbl;\red255\green255\blue255;}

    \paperw11900\paperh16840\margl1440\margr1440\vieww10800\viewh8400\viewkind0

    \pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0



    \f0\fs24 \cf0 Hello}

    How can I get it no to give all this random stuff before it? Is it because I am using Xcode or .rtf files. Maybe I should try it using SublimeText and terminal, the only reason I wanted to use Xcode is I need to do an assignment and it is much easier to do on xcode.
    --- Post Merged, Feb 27, 2018 ---
    Thank you!
     
  2. neliason macrumors 6502

    Joined:
    Oct 1, 2015
    #2
    RTF files have formatting code in them. That is what you are seeing. The source file you read should be plain text.

    You can read RTF files but you would need a library that handles the formatting.
     
  3. tombaxterlfc thread starter macrumors newbie

    Joined:
    Feb 27, 2018
  4. neliason macrumors 6502

    Joined:
    Oct 1, 2015
    #4
    You can use the Mac’s Text program. Just save the source file as plain text not RTF. Sublime works great too.
     
  5. tombaxterlfc thread starter macrumors newbie

    Joined:
    Feb 27, 2018
    #5
    Of course, thank you!
    --- Post Merged, Feb 27, 2018 ---
    It works, appreciate the help.
     

Share This Page

4 February 27, 2018