【发布时间】:2018-01-25 10:51:01
【问题描述】:
我正在尝试将我的程序从能够读取硬编码的 name.txt 更改为任何名称或可读类型。我在正确传递 argc 和 argv 时遇到问题,并且给出了诸如“main 中的参数太少”之类的错误,我试图在使用的函数中初始化这两个,但未确定。我将如何正确使用这两个工具? (箭头指向 arg 线) 这是我的代码:
#include <stdio.h>
#include <stdlib.h>
// Pointer to store numbers
int *pointerNUM;
// Read in the parts file and returns the length
int readFile(int argc, char *argv[]) //<-----------------------------
{
// File pointer
FILE *fptr;
// numberOfNUM for number of numbers
// cntVAR for counter variable
int numberOfNUM, cntVAR;
// Open the file for reading
fptr = fopen(argv[1], "r"); //<-----------------------------------------
// Check that it opened properly
if (fptr == NULL)
{
printf("Cannot open file \n");
exit(0);
}// End of if condition
// Reads number of numbers in the file
fscanf(fptr, "%d", &numberOfNUM);
// Dynamically allocates memory to pointer pointerNUM
pointerNUM = (int *) calloc(numberOfNUM, sizeof(int));
// Loops numberOfNUM times
for(cntVAR = 0; cntVAR < numberOfNUM; cntVAR++)
// Reads each number and stores it in array
fscanf(fptr, "%d", &pointerNUM[cntVAR]);
// Returns the length of the numbers
return numberOfNUM;
}// End of function
// Function to display numbers
void display(int numberOfNUM)
{
int cntVAR;
// Loops numberOfNUM times
for(cntVAR = 0; cntVAR < numberOfNUM; cntVAR++)
// Displays each number
printf("%4d, ", pointerNUM[cntVAR]);
}// End of function
// Function for insertion sort
void insertionSort(int numberOfNUM)
{
int x, key, y;
// Loops numberOfNUM times
for (x = 1; x < numberOfNUM; x++)
{
// Stores i index position data in key
key = pointerNUM[x];
// Stores x minus one as y value
y = x - 1;
/*
Move elements of pointerNUM[0..x - 1], that are greater than key,
to one position ahead of their current position
*/
while (y >= 0 && pointerNUM[y] > key)
{
// Stores pointerNUM y index position value at pointerNUM y next index position
pointerNUM[y + 1] = pointerNUM[y];
// Decrease the y value by one
y = y - 1;
}// End of while
// Stores the key value at pointerNUM y plus one index position
pointerNUM[y + 1] = key;
}// End of for loop
}// End of function
// main function
int main()
{
// To store the numbers of number in file
int numberOfNUM;
// Calls the function to read numbers and stores the length
numberOfNUM = readFile(); <-----------------------------------------
// Calls the function to displays the numbers before sorting
printf("\n Before sort : ");
display(numberOfNUM);
// Calls the function for sorting
insertionSort(numberOfNUM);
// Calls the function to displays the numbers after sorting
printf("\n After sort: ");
display(numberOfNUM);
}
【问题讨论】:
标签: c parameter-passing argv argc