2
votes

The following code create a file file.text and prints the following in the file "

1 2 
3 4

What is the most efficient way to print the value 4 on the console. In actual case I have a 2000 x 2000 matrix, and I have to access let say the value [2000][1500] and print the same on console. by efficient I mean how quickly the pointer can go there, fetch the data, and send it to the display buffer.

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

int main()
{
   FILE * fp;

   fp = fopen ("file.txt", "w+");
   fprintf(fp, "%s %s %s %d", "1", "2", "\n" "3", 4);


   fclose(fp);

   return(0);
}
1
If you want to do it quickly you might need to assume the file is correctly filled. If you know your numbers are only 1 digit long you can multiply (2 (1 digit + 1 space) by the number of entries in one line + 1 (the "\n")) by y: the number of the line you wish to get (in this case i think 2000?) and then add (2 (same) times x). If your numbers are not always 1 digit long, you need to read the file by chunks, count the "\n"'s and then count the spaces.Eregrith

1 Answers

1
votes

Assuming the "file" need not be a text file, and the data to be stored need not be formatted in the form of matrix (i.e. including spaces and newlines).

You can do the following:

Step 1. Open file in binary mode.
Step 2. Write the matrix (suppose A[2000][2000])data in the file using fwrite.
Step 3. Now your file is ready, you want to read element at position say [1500][1000].
Step 4. That will be ((1500*2000) + 1000)th integer written in the file, so use fseek to get the file pointer to that position.
Step 5: Read the integer from that position using fread.