need to read data from file through cmd line arguments


I have a file named config.txt
which has following data
1
2
3
4
//config.txt
 Number of node = 11
Link delay = 1 2 3 4 5 6 7 8 9 10


now I want to read config.txt from command pronpt

also I want to read number of nodes from config.txt and I want to use it for calculation of delay between nodes.

as follows
1
2
3
4
5
6
7
8
9
int main(int argc, char* argv[]) {
 float delay = 0, d[10];
 FILE* fp = fopen(argv[1],"w");
 int i, num_nodes = readArgFromFile(fp,d);
 for(i = 1; i < num_nodes; i++)
 delay += d[i-1];
 printf("Overall Packet Delay is %2.1f seconds\n",delay);
 fclose(fp);
 }


But I do not know hoe to read data from file and how to use it fro computation
please reply
First, this sounds like "Beginner" Forum material rather than "UNIX/Linux" Forum. I believe that you can move the thread yourself by editing the first post.

Second. You seem to be using C rather than C++. There is nothing wrong with that, but C++ has more options for I/O.

Your example has already some issues:
* You don't verify that there is argv[1].
* Input data contains 11 elements, but your program cannot store more than 10.
* You ignore first data point in the sum of delays.

What should readArgFromFile do?
Perhaps read first line until it finds '=' and then store the first integer after it?
Ignore the second line up to '=' and then read up to num_nodes float values?

Do you know how to read from stdin? It is quite similar to a FILE*.
Thanks for reply.
I know this program is wrong.

Please guide me two calculated link delay between nodes.

I have used argv because I want to read file name from cmd prompt.

I have 11 nodes.
link delay between node 1 and node 2 is 1.
link delay between node 2 and node 3 is 2.
I want to read this from config,txt

I have to calculate total link delay.

please guide how to do this
Think about:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <numeric>
#include <iterator>
#include <fstream>
#include <iostream>

void foo( std::istream & in )
{
  typedef std::istream_iterator<int> Iter;
  std::cout << std::accumulate( Iter(in), Iter(), 0 ) << '\n';
}

int main( int argc, char *argv[] )
{
  if ( 1 < argc )
    {
      std::ifstream file( argv[1] );
      foo( file );
    }
  else
    {
      foo( std::cin );
    }
  return 0;
}

$ tail -1 config.txt | sed s/.*=// | ./a.out
55
$
Topic archived. No new replies allowed.