如何从命令行读取文件

时间:2016-02-01 00:37:18

标签: c file file-io input

我开始学习C并且我应该读取我拥有的txt文件,并且我试图从命令行打开它。我应该从txt文件中获取数据并对其进行解码,但是现在我只是尝试将其写入新文件并且似乎无法将我的输入文件读入并随后写入新的txt我要创建的文件。我尝试使用while循环打印出文件的内容,但无济于事。 任何帮助,将不胜感激。

编辑: 我的程序目前没有通过我的while循环打印任何东西,并给我一个“分段错误”错误,并没有写入我的新txt文件,虽然它创建它,没有任何内容存储在文件中。 该文件的内容很长,但遵循以下模式:

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

我的代码:

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;
    }

1 个答案:

答案 0 :(得分:1)

首先,
帖子的标题要求如何从命令行中读取文件 这是一个简单的例子:

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;
}

接着,
您提供的输入文件的文本长度至少为1060字节,最长的行为976字节。您创建的行缓冲区(char line[256];)不够大。如果您可以以编程方式预先确定正在读取的内容,则可以在尝试写入之前在运行时调整缓冲区大小。在下面的示例代码中查看可以在运行时完成的方式(读取包含未知内容的文本文件)。

接下来,改变:

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

要:

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

接下来,检查每次调用的输出fopen()

示例:

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

阅读包含未知内容的文本文件。有时在尝试将文件读入缓冲区之前测试文件的内容是有帮助的。例如,此示例函数将显示行数和文本文件中的最长行:(传递输入文件的path_name,它将返回文件中的最长行,并更新int *lc 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;
}

使用上述功能,可以读取您的文件,并将内容放入输出文件中。

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);


}