user4276463
user4276463

Reputation:

How to read file from the command line

I'm starting out learning C and I'm supposed to read in a txt file that I have and I am attempting to open it from the command line. I am supposed to take the data from the txt file and decode it, but for now I'm just attempting to write it to a new file and can't seem to get my input file to read in and subsequently write to the new txt file I want to create. I've tried using a while loop to print out the contents of the file but to no avail. Any help would be appreciated.

Edit: My program currently does not print anything out through my while loop and gives me a "segmentation fault" error and does not write to my new txt file, although it creates it, nothing is stored in the file. The contents of the file are long, but follows this pattern:

encodedLength,bits,base64

12,64,AAAAAAAAAEA=
12,64,vvj7ZlmphkA=
12,64,k+Oj/7LbkUA=
56024,64,qZzGabZBf0CQT8vJMEJ/QISgOVMaRH9AwB2+bG9Lf0BpLEli0FF/QKEpqrloU39A9klOPONTf0CETlNyiV9/QKUKUN66Yn9A7CEjAnlsf0ATW5MDlnF/QG1IilrIdH9AhU5hRvF0f0DHblZlf3t/QLHq2kXRe39AF951+tqCf0C7/5Gv+YN/QD6plms3in9AWwvIRy2Lf0BY5BOuJJR/QDOqDBoxm39AnD3CrKOxf0DOKmoimrJ/QGh1pV4Vs39AGRJSh2ezf0CZnRzF4rN/QJ2y6tkLtH9Aj2XT7jS0f0ButtYDXrR/QDql9BiHtH9A8TEtLrC0f0AqJe5YArV/QGJZu24SvH9ArdxKi3XDf0BTUi3Jx8N/QLmkMUZsxH9ARgiIpwLLf0DsSAGSWc9/QBxGuUw1039ALnyq8dnTf0APkUWYftR/QBnhLsKn1H9AQZAiU07ef0D2a2fCneN/QBSk4Cnw439ACS3FXRnkf0DqU8SRQuR/QLgY3sVr5H9AdHsS+pTkf0AcfGEuvuR/QJS+/yPN539AoG68zonqf0B/kCovZ+5/QKcy0WmQ7n9AvXKSpLnuf0C8UG7f4u5/QKzMZBoM739AiOZ1VTXvf0BSnqGQXu9/QAn058uH739AredIB7Hvf0BAeKEIbvJ/QJCG4UWX8n9AzTI8g8Dyf0D3fLHA6fJ/QAtlQf4S839AD+vrOzzzf0ABD7F5ZfN/QN/QkLeO839AqzCL9bfzf0BkLqAz4fN/QArKz3EK9H9AnQMasDP0f0Aa237uXPR/QIdQ/iyG9H9A4WOYa6/0f0ApFU2q2PR/QF1kHOkB9X9Acsxj5ab1f0AtRjtpjfh/QMP3qG4y+X9A+u5GsFv5f0AdhP/xhPl/QC630jOu+X9ALIjAddf5f0AU98i3APp/QOwD7Pkp+n9Axo7rGoT+f0BB0h6l1v5/QHGNvC8p/39A7FczdVL

My code:

int main(int argc, char* argv[])
    {
        char fileString[256];
        char line[256];

        /*Pseudocode
        Need to convert base 64 string back into 32 bit floats

        Algorithm:
        Open up file in command line
         Skip first line of txt file
         Read file in line by line
         Convert each line from base64 to 32 bit floats (truncated to 3 decimal places), end each with a new line
         Store all of this in an output file called p1_output.txt

         */

        printf("Please enter your file name (include file extension): ");
        scanf("%s", &fileString);
        printf("%s\n", fileString);

        FILE *inputFile = fopen(fileString, "r");
        FILE *outputFile = fopen("p1_output.txt", "w+");

        while(fgets(line, 256, inputFile))
        {
            printf("%s", line);
            fputs(line, outputFile);

        }

        return 0;
    }

Upvotes: 0

Views: 6877

Answers (1)

ryyker
ryyker

Reputation: 23208

First,
The title to your post asks How to read file from the command line.
Here is a simple example:

int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        printf( "usage: %s filename", argv[0] );
        return 0; //should be two arguments, exe name & file path/name
    }
    //if Windows:
    if(GetFileAttributes(argv[1]) != 0xffffffff) //file exists
    {
        //do something with file;
        FILE *file = fopen( argv[1], "r" );
        // and so on...
    }
    //if Linux:
    if (0 == access(path, 0))//file exists
    { 
        //do something with file;
        FILE *file = fopen( argv[1], "r" );
        // and so on...

    } 

    return 0;
}

Next,
The input file you provide has text at least 1060 bytes long, with the longest line being 976 bytes. The line buffer you created ( char line[256]; ) is not big enough. If you can programmatically predetermine the contents of what you are reading then you can size the buffer at run-time before trying to write to it. See a way this can be done at run-time in example code below (Reading a text file with unknown content).

Next, change:

scanf("%s", &fileString);
            ^

To:

scanf("%s", fileString);//do not need the & for reading in strings
            ^

Next, check the output of each call to fopen()

Example:

FILE *outputFile = fopen("p1_output.txt", "w+");
if(!outputFile ) return -1;
//else continue using outputFile 

Reading a text file with unknown content. Sometimes it is helpful to test the file for its contents before trying to read it into buffers. This example function, for example, will reveal the number of lines, and the longest line in a text file: (pass it the path_name of input file and it will return the longest line in the file, and update int *lc with linecount)

int longestline(const char *filename, int *lc)
{
    FILE *fp;
    int cnt=0, cntKeep=0;
    int c;
    fp = fopen(filename, "r");
    if(!fp) 
    {
        *lc = 0;
        return 0;
    }
    (*lc) = 0;
    while ( (c = fgetc ( fp) ) != EOF )
    {
        if(c != '\n') 
        {
            cnt++;
        }
        else 
        {
            cnt = 0;
            (*lc)++; //update line counter
        }
        cntKeep = cntKeep < cnt ? cnt : cntKeep;//update longest line counter
    }
    if(cnt > 0) (*lc)++;//last line may not have '\n'
    fclose(fp);
    return cntKeep;
}

Using the function above, this was able to read your file, and put the contents into an output file.

int main(void)
{
    FILE *in;
    FILE *out;
    int linecount;

    int longest = longestline("C:\\dev\\play\\file2.txt", &linecount);

    char string[longest+2];//create buffer with known longest line with room for white space and NULL

    in = fopen("C:\\dev\\play\\file2.txt", "r");
    if(!in) return 0;
    out = fopen("C:\\dev\\play\\output.txt", "w");
    if(!out) return 0;

    while(fgets(string, longest+2, in))
    {
        fputs(string, out);
    }
    fclose(in);
    fclose(out);


}

Upvotes: 1

Related Questions