Search code examples
ciofgetsargv

C - working with Text Files


Basically, I'm working on a small program in C (again, not a homework task, just some experimentation while I'm away from Uni :) ). My goal is to take a file containing lots of words all seperated by spaces, loop through the file, and whenever a space is found, replace that for a \n thus creating a large list of words.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
/*
 * 
*/
int main(int argc, char** argv) {

char myFile[100];
int i;
FILE *file;
while(argc--) {
    printf("%s\n", *argv++);
}

return 0;
}

Very basic what I have so far, what I need to do next is to take the arguement and whack it in the myFile array, so that I can use that as the fopen, or maybe there is another way to do this?

Beyond that, my idea was to then read a line, into an array via fgets, loop through it char by char, searching for ' ', if I find it, replace is for \n, then rewrite that line to the file. Does this sound sensible, doable?

Regards,

and Thanks!


Solution

  • the simplest way is to open the file in binary mode

    FILE *fpIn = fopen( argv[1], "rb" );
    

    then open a new file for writing

    FILE* fpOut =  fopen( "tmp.out", "wb" );
    

    and read byte by byte from fpIn using fgetc and write using fputc to the new file

    before writing check if the byte is a space (use isspace()), write a '\n' instead.

    then delete original and rename tmp.out to argv[1]