How should I fill an array of ints from a file using command line args? The size of the file and the no. of elements may

How should I fill an array of ints from a file using command line args? The size of the file and the no. of elements may

By : caricature
Date : October 24 2020, 06:10 PM
This might help you There are multiple problems in the code:
is a C++ header, do not mix C and C++. printf(stderr, "Error, too many arguments supplied."); should produce a warning about the type mismatch on its first argument. use fprintf to print to stderr. The file is open in text mode, not binary mode, so ftell() might not return the number of bytes in the file. file open failure is not tested. Allocating fileSize * sizeof(int) is overkill. The numbers are in text format, so at most fileSize / 2 numbers can by found in the file, and likely much less than that. failure to allocate bytes does not mean the file is empty. You should reallocate the array as you read more numbers from the file. This allows also for reading from devices that are not seekable such as terminals and named pipes. arraySize = sizeof(numArray) / sizeof(numArray[0]) does not compute the number of elements in the array because numArray is a pointer to an array, not an array. Furthermore you should just keep the number of actual numbers read, which is the final value of i in the for loop. you should test the return value of fscanf(): 1 means the conversion succeeded, 0 means invalid input is present, that cannot be converted to an integer, EOF means end of file, or possibly I/O error.
code :
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {

    if (argc != 2) {
        fprintf(stderr, "The program expects a single command line argument\n");
        return 1;
    } else {
        int *numArray = NULL;
        size_t arraySize = 0;
        size_t arrayCount = 0;
        FILE *inputFile = fopen(argv[1], "r");
        int res, num;

        if (inputFile == NULL) {
            fprintf(stderr, "Cannot open file %s: %s\n", strerror(errno));
            return 1;
        while ((res = fscanf(inputFile, "%d", &num)) == 1) {
            if (arrayCount >= ArraySize) {
                size_t newSize = arraySize ? arraySize * 2 : 32;
                int *newArray = realloc(numArray, newSize * sizeof(int));
                if (newArray == NULL) {
                    fprintf(stderr, "Out of memory for %zu elements\n", newSize);
                numArray = newArray;
                arraySize = newSize;
            numArray[arrayCount++] = num;
        if (res != EOF) {
            fprintf(stderr, "Invalid input for element %zu\n", arrayCount);
        if (arrayCount == 0) {
            if (res == EOF) {
                fprintf(stderr, "File %s is empty\n", argv[1]);
            return 1;
        ...  // do something with the arrayCount elements in numArray
    return 0;

Share : facebook icon twitter icon
Send command line args while opening a file

Send command line args while opening a file

By : Ahmed El-Sayed Ali
Date : March 29 2020, 07:55 AM
With these it helps I assume you want to run it from a shell script of some sort? If so, you should be able to use the open command (manpage) to start it:
code :
$ open /Applications/MyApp.app --args /path/to/file.pdf
C++ command line args (file) not found?

C++ command line args (file) not found?

By : Hema
Date : March 29 2020, 07:55 AM
Does that help I have the following main method:
code :
int main ( int argc, char *argv[] )
argc = 2
argv[0] = "Project2.exe" 
argv[1] = "C:\Differnt Filepath\args.txt"
In a batch file I want to run an exe with command line args which are contained in a text file

In a batch file I want to run an exe with command line args which are contained in a text file

By : user3018739
Date : March 29 2020, 07:55 AM
it helps some times In a batch file I would like to open and run an .exe with command line arguments. But instead of listing all the arguments--there are a lot--I would like to put the arguments in a file and then put the name of the file after the .exe file.
code :
thisbatchname yourtextfilename
SET "args="
FOR /f "usebackq delims=" %%a IN ("%~2") DO SET "args=!args! %%a"
ECHO "%~1%" %args%

thisbatchname executablename yourtextfilename
How to concatenate command line args for a batch file?

How to concatenate command line args for a batch file?

By : Anne Parker
Date : March 29 2020, 07:55 AM
like below fixes the issue I'm currently attempting to concatenate my command line arguments with this: , Can't you just do:
code :
SET subject=%*
Setlocal EnableDelayedExpansion
for %%a in (%*) do set subject=!subject! %%a
echo %subject%
How do I set an array size using command line args[]? Java

How do I set an array size using command line args[]? Java

By : Guillaume Boudreau
Date : March 29 2020, 07:55 AM
seems to work fine You will ArrayIndexOutOfBoundsException if you don't pass 11 arguments to the program. You are trying to get the integer value of index 10 of args array.
Related Posts Related Posts :
  • Random function stuck on one number
  • printf following zeros to a certain degree
  • Measuring CPU clocks consumed by a process
  • How is a CRC32 checksum calculated?
  • Tips on redefining a register bitfield in C
  • Converting a program from c to bash script
  • Static library not included in resulting LLVM executable
  • What is the meaning of "wild pointer" in C?
  • Reading DWORD from binary file
  • Efficient way to find divisibility
  • Whats the fastest, portable way to hash pointers we know are pointer aligned to a fixed size int?
  • Why does my summation program behaves weird?
  • How to determine values saved on the stack?
  • Thread scheduling C
  • C - converting to 2s complement
  • wireless networks c program
  • From where does the uboot get the information about flash, RTC, RAM in uboot/kernel development
  • printf behaviour in C
  • Measure size and way-order of L1 and L2 caches
  • Efficient copy of entire directory
  • Efficient way to create/unpack large bitfields in C?
  • getnameinfo prototype asks for sockaddr not sockaddr_in?
  • Linked List Sorting with Strings In C
  • Typecasting a floating value or using the math.h floor* functions?
  • Problem implementing sorting algorithm in C with an array of structs
  • How to copy a ram_base file to disk efficiently
  • How to fix casting a pointer to an integer?
  • How to round floating point numbers to the nearest integer in C?
  • PIC C - Sending 200 values over USB, but it only sends 25 or so of them
  • How do you return a string from a function correctly in Dynamic C?
  • Monotonic clock on IRIX
  • setsockopt (sys/socket.h)
  • How to make C program wait (on Linux)?
  • i find a problem using atoi() method in ansi c?
  • Why is this array being initialized in an odd way?
  • How to execute commands in chroot?
  • Microsecond (or one ms) time resolution on an embedded device (Linux Kernel)
  • Question about variable definitions in functions
  • SMTP on C: STARTTLS via OpenSSL
  • fetch value of ipaddress
  • Binary expressions in C
  • Why do char * and char ** have the same value?
  • problem in allocating kernel memory by malloc() from user space?
  • dangling pointer, reason for value change after free()?
  • How to compile C program with multiple files in Xcode
  • Can you make an incrementing compiler constant?
  • Reading data from text file in C
  • SQLite's test code to production code ratio
  • Displaying an inverted pyramid of asterisks
  • sd spi mode in C language
  • printf("%2d") in C programming
  • Add a certain number of bytes to a void pointer in C
  • How should I protect against hard link attacks?
  • What's the difference between unsigned long/long/int in c/c++?
  • Get an input from keyboard without 'return' in C
  • How to convert if to switch-case in c
  • C: swapping two pointer value
  • What does \x mean in c/c++?
  • run a command line argument prog
  • Pass a dynamic structure by reference? [C]
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk