首页 > 解决方案 > 如何在 C 控制台程序中读取 .txt 文件?

问题描述

我有一个程序,我必须从用户输入中读取数据对列表,例如:

1,2 3,4 5,6

或者:

1,2
3,4
5,6
4,3

这是我的代码

#include <stdio.h>
#include <stdlib.h>


void swap(int* a, int* b)
{
    int t = *a;
    *a = *b;
    *b = t;
}

int partition(int arr[], int low, int high)
{
    int pivot = arr[high];    // pivot 
    int i = (low - 1);  // Index of smaller element 

    for (int j = low; j <= high - 1; j++)
    {
        // If current element is smaller than the pivot 
        if (arr[j] < pivot)
        {
            i++;    // increment index of smaller element 
            swap(&arr[i], &arr[j]);
        }
    }
    swap(&arr[i + 1], &arr[high]);
    return (i + 1);
}

void quickSort(int arr[], int low, int high)
{
    if (low < high)
    {
        /* pi is partitioning index, arr[p] is now
           at right place */
        int pi = partition(arr, low, high);

        // Separately sort elements before 
        // partition and after partition 
        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}

void printArray(int arr[], int size)
{
    int i;
    for (i = 0; i < size; ++i)
        printf("%d ", arr[i]);

}
int main()
{
    int n1, n2;
    int x[10] = { 0 };
    int y[10] = { 0 };

    int capacity = 0;

    int n = sizeof(x) / sizeof(x[0]);

    for (size_t i = 0; i < n; ++i)
    {

        scanf_s(" %d , %d [^\n]", &n1, &n2);
            x[i] = n1;
            y[i] = n2;

    }

    for (int j = 0; j < n; ++j)
    {
        printf("%d , %d\n", x[j], y[j]);

    }
    quickSort(x, 0, n-1);
    printArray(x, n);

    printf("Minimum is: %d", x[0]);
    printf("Maximum is: %d", x[n-1]);
    return 0;
}

但是,当我尝试通过在 CMD 中运行命令将文件传输到控制台时:program.exe some.txt

它会给我:

-858993460 , -858993460
-858993460 , -858993460
...

但是当我输入 txt 文件中的值时,我得到了正确的输出。

无论如何让 C 控制台程序接受用户输入和 .txt 文件?

我的教授展示了一个使用 scanf_s 的示例,他可以只使用 debug.exe 和 txt 文件来获取输入,他说这会诱使程序认为它来自键盘缓冲区。我对这将如何工作感到困惑。

来自 CMD 的错误代码:

C:\Users\username\Downloads\Project\test_files>sort.exe book.txt -> sort.exe < book.txt

该进程无法访问该文件,因为它正被另一个进程使用。

另一个错误是一个红色的弹出窗口,说我应该得到一个最终版本(它是从窗口弹出的)。

标签: cfileconsoleuser-input

解决方案


你的命令行是错误的。

代替:

sort.exe < book.txt -> sort.exe < book.txt

你要:

sort.exe < book.txt | sort.exe > book2.txt

但无论如何,我不确定你到底想在这里做什么......

请注意,您需要其他文件book2.txt而不是,这就是错误book.txt的原因。The process cannot access the file because it is being used by another process.


推荐阅读