Accessing random nos from file and displaying on console? - c

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);
}

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.

Related

What do I need to do to read a file then pick a line and write it to another file (Using C)?

I've been trying to figure out how I would, read a .txt file, and pick a line of said file from random then write the result to a different .txt file
for example:
.txt
bark
run
car
take line 2 and 3 add them together and write it to Result.txt on a new line.
How would I go about doing this???
I've tried looking around for resources for fopen(), fgets(), fgetc(), fprintf(), puts(). Haven't found anything so far on reading a line that isn't the first line, my best guess:
-read file
-print line of file in memory I.E. an array
-pick a number from random I.E. rand()
-use random number to pick a array location
-write array cell to new file
-repeat twice
-make newline repeat task 4-6
-when done
-close read file
-close write file
Might be over thinking it or just don't know what the operation to get a single line anywhere in a file is.
just having a hard time rapping my head around it.
I'm not going to solve the whole exercise, but I will give you a hint on how to copy a line from one file to another.
You can use fgets and increment a counter each time you find a line break, if the line number is the one you want to copy, you simply dump the buffer obtained with fgets to the target file with fputs.
#include <stdio.h>
#include <string.h>
int main(void)
{
// I omit the fopen check for brevity
FILE *in = fopen("demo.c", "r");
FILE *out = fopen("out.txt", "w");
int ln = 1, at = 4; // copy line 4
char str[128];
while (fgets(str, sizeof str, in))
{
if (ln == at)
{
fputs(str, out);
}
if (strchr(str, '\n') && (ln++ == at))
{
break;
}
}
fclose(in);
fclose(out);
return 0;
}
Output:
int main(void)

How to write a floating point array to a file in C?

I have an float array, that has 189 elements (running from index 0 to index 188). I'm having trouble writing this array out to a file. Suppose the first element is 45.6, and the second element is 67.9, I want my output file to look like this:
0, 45.6
1, 67.9
and so on. I've tried the function shown below, and the result is my output file has odd characters in it.
void writeCorrelationToFile(float slidingCorrelator[])
{
FILE *fp;
fp=fopen("CorrelationResult.txt","w");
printf("inside writeCorrelationToFile, writing out array using fwrite \n");
fwrite(slidingCorrelator,4,sizeof(slidingCorrelator),fp);
fclose(fp);
}
I get an output file like this:
�'���۽l^��(���!>
I have also tried setting sizeof(slidingCorrelator) to 189, but that also did not help.
The fwrite() function writes binary data. What you want to write is the human readable (i.e. text) representation of your float values, not the binary representation.
You can do this using fprintf():
float slidingCorrelator[N];
FILE *fp;
// ... fill the array somehow ...
fp = fopen("CorrelationResult.txt", "w");
// check for error here
for (unsigned i = 0; i < N; i++) {
fprintf(fp, "%d, %f\n", i, slidingCorrelator[i]);
// check for error here too
}
fclose(fp);
Don't forget to check the return value of those functions to detect errors. For more information, see:
man 3 fwrite
man 3 fprintf
man 3 fopen

C - Append on 2nd line of file

Im trying to append on the 2nd line of my txt file. The format I want for my txt file is the following:
1 2 3 4 5
1.2 3.5 6.4 1.2 6.5
Basicly, I want to append on the first two lines of the file.
void write_stats(int tries, int num_letters, int tries_sucess)
FILE *stats;
stats = fopen("C:\\Users\\rjmal\\Documents\\CLION PROJECTS\\JogoDaForca\\stats.txt", "a");
if(stats == NULL)
{
printf("can't open file\n");
exit(0);
}
fprintf(stats," %d\n",tries);
fprintf(stats," %f",(float)tries_sucess/num_letters);
fclose(stats);
}
How do I make that without making a new line on the file everytime I run my program?
With the code I made, I get something like:
1
3 1.5
1 2.3
Due to the way files and lines are considered in computers, you can not vertically print as you desire. Instead, what you can do is storing all these numbers (i.e. tries AND (float)tries_sucess/num_letters) in two arrays and printing the contents of each array on the same line in that order. In effect, this would be buffering your content before printing and formatting it as you desire.
In that way, you can print all the data into two lines, which now correspond to an array, each.
Alternatively, you can create two char arrays and consider them as actual string buffers and use sprintf to record into them. Then, once you're done, you can print each char array through a single fprintf call.
Assuming you created two sufficiently long char arrays, below is a sample code for new write_stats. It now only serves to record the stats into two buffers.
void write_stats(int tries, int num_letters, int tries_sucess, char* buffer1, char* buffer2)
{
sprintf(buffer1 + strlen(buffer1)," %d\n",tries);
sprintf(buffer2 + strlen(buffer2)," %f",(float)tries_sucess/num_letters);
}
Note that you need to initiate the buffers with 0 to be able to easily make use of strlen function as I did. Also, you will eventually (i.e. when you are done calling write_stats ) need to call fprintf, in a block that buffer1 and buffer2 are defined in, as follows.
FILE *stats;
stats = fopen("C:\\Users\\rjmal\\Documents\\CLION PROJECTS\\JogoDaForca\\stats.txt", "a");
if(stats == NULL)
{
printf("can't open file\n");
exit(0);
}
fprintf(stats,"%s\n%s", buffer1, buffer2);
fclose(stats);
Since there are quite a few details to keep in mind, I think it is best you see this idea at work. See here for a working implementation, with some comments to help elaborate some details. As you may observe, the output given there is horizontal and is in 2 lines, as you described and as given below.
1 3 13 55 233
2.000000 1.600000 1.619048 1.617978 1.618037

weird issue with output to text in C

This error is driving me nuts. Please help. The code compiles in gcc in terminal and in codeblocks IDE. I'm using Linux and C. It compiles and runs but theres no output in the second text file "onlydata.txt".
#include <stdlib.h>
#include <stdio.h>
/* Data Looks Like This...
E1 101223 9.2
E1 120231 8.4
E2 121212 400.2
I need this....
9.2
8.4
*/
struct Data
{
char *specimen;
int date;
double result;
};
int main()
{
char szBuffer[256];
unsigned int iCt=0;
Data* pData=NULL;
FILE* fpIn=NULL;
fpIn=fopen("data.txt","r"); //Open "Data.dat for read "r" access.
if(fpIn) //and loop through data to count lines.
{ //in iCt
while(!feof(fpIn))
{
fgets(szBuffer,256,fpIn);
iCt++;
}
fclose(fpIn);
}
printf("iCt = %d\n\n",iCt); //Allocate a buffer of Data type
pData=(Data*)malloc(iCt*sizeof(Data)); //to hold iCt objects
if(pData)
{
fpIn=fopen("Data.txt","r"); //Open "Data.dat for read "r" access.
if(fpIn) FILE *fp=NULL;
{
iCt=0;
while(!feof(fpIn)) //read data from text file into buffer
{
fscanf(fpIn,"%s%i%f",
&pData[iCt].specimen,
&pData[iCt].date,
&pData[iCt].result);
// printf("%10.2f\t%4.2f\t%f\t%f\t%f\t%u\t%4.2f\n",
// pData[iCt].specimen,
// pData[iCt].date,
// pData[iCt].result,
iCt++;
FILE *np=NULL;
np = fopen("onlydata.txt","w");
if(np)
fprintf (np," ", &pData[iCt].result);
fclose(np);
}
fclose(fpIn);
}
free(pData);
}
getchar();
return 0;
}
Linux filenames are case sensitive. The second fopen() will fail if the file is called "data.txt".
The actual problem you have stems from the following line:
fprintf (np," ", &pData[iCt].result);
It simply outputs a space to the file. I think you forgot a %f.
EDIT Missed the other obvious error noted by Didier Trosset. :)
you need to have specifier in your fprintf for the result, without the specifier it just writes a whitespace into the file
You should open you destination file only once, at the same time you open your source file.
Right now, for every line of the source file, you open the destination, truncate it, and write one line. In the end, you only got a single line (the last one) in your destination file.
Furthermore, your fprintf does only write a single space character: your format string should be "%f" or at least contain one %f. Actually, the parameter &pData[iCt].result is not used.
Note also that this parameter should not be passed by address, but by value: (remove the &).

Inserting a value into a file

In the code below, I have saved the values 1 - 9 in an Excel file and I want to insert an "a" between "4" and "5". I have set the pointer to position 7 but it is still inserting it at the end. Please help me understand this.
FILE *ExcelFile = fopen("testdata.csv","a");
if (ExcelFile == NULL)
return -1;
fprintf(ExcelFile,"1 2 3 4 5 6 7 8 9");
fseek (ExcelFile, 7, SEEK_SET );
//printf("pos is %ld bytes\n", pos);
fprintf(ExcelFile,"a");
fclose(ExcelFile);
The reason this does not work is because you are opening the file for appending (the "a" flag in the fopen call). Whenever you write to the file the data you write will always be appended. If your file does not exists before opening, use fopen("testdata.csv","w") instead.
You can't just "insert" the value into a file. You must open a new file, copy the first part of the first file, then your value, then the rest, and then replace the old file with the new one, or, if the file is small, read it into memory, clear the file, and then write the correct file.

Resources