I have a text file with one number in each line.
I want to read a specific number of lines from this file , lets say the first 20, what is the way to do it?
I have the following piece of code.
FILE *ft;
ft=fopen(filename,"r");
for(int k=1; k<Nt+1; k=k+1)
{
fscanf(ft,"%lf\n",&curve3[k]);
printf("%lf\n",curve2[k]);
}
EDIT: I changed my code to
FILE *ft;
ft=fopen(filename,"r");
int k=1;
while(!feof(ft))
{
if(k<=Nt)
{
fscanf(ft,"%lf\n",&curve2[k]);
//printf("%lf\n",curve2[k]);
}
k=k+1;
}
It still doesn't seem to work.
With this code you can read a file line by line and hence read a specific line from the text file. So, you can modify the code.
lineNumber = x;
static const char filename[] = "file.txt";
FILE *file = fopen(filename, "r");
int count = 0;
if ( file != NULL )
{
char line[256]; /* or other suitable maximum line size */
while (fgets(line, sizeof line, file) != NULL) /* read a line */
{
if (count == lineNumber)
{
//use line or in a function return it
//in case of a return first close the file with "fclose(file);"
}
else
{
count++;
}
}
fclose(file);
}
else
{
//file doesn't exist
}
Related
I am trying to write this program in C. The intent of the program is to run a designated keyword search on one file, find the information stored on that line, and then copy that information to the same location in another file. The keyword is utilized to determine the line in the file to be copied and to replace. I am using Microsoft Visual. Built in ".c" I am receiving this message: " (process 24612) exited with code -1073741819"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable : 4996)
#define MAX_LENGTH 1000
void locate(const char* keyword, int start, int end, int lineCount, char* line, int* a, int* a_index) {
if (lineCount >= start && lineCount <= end) {
if (strstr(line, keyword) != NULL) {
a[*a_index] = lineCount;
(*a_index)++;
}
}
}
void replaceLines(const char* filename1, const char* filename2, const char* keyword, int start, int end) {
char buffer[MAX_LENGTH];
char line[MAX_LENGTH];
int lineCount = 0;
int i;
int a[20];
int a_index = 0;
// Open the first file in read
FILE* file1 = fopen(filename1, "r");
if (file1 == NULL) {
printf("Error opening file %s\n", filename1);
exit(1);
}
// Open the second file in read
FILE* file2 = fopen(filename2, "r");
if (file2 == NULL) {
printf("Error opening file %s\n", filename2);
exit(1);
}
// Read the first file into a buffer
while (fgets(buffer + strlen(buffer), MAX_LENGTH, file1)) {
;
}
// Close the first file
fclose(file1);
// Open the first file in read/write
file1 = fopen(filename1, "w+");
if (file1 == NULL) {
printf("Error opening file %s\n", filename1);
exit(1);
}
// Read file1 line by line
while (fgets(line, MAX_LENGTH, file1)) {
lineCount++;
locate(keyword, start, end, lineCount, line, a, &a_index);
}
lineCount = 0; //reset lineCount
// Read file2 line by line and copy line from file2 to buffer using the line found in file1 keyword search
while (fgets(line, MAX_LENGTH, file2)) {
lineCount++;
if (lineCount >= start && lineCount <= end) {
if (strstr(line, keyword) != NULL) {
strncpy(buffer + a[a_index] * MAX_LENGTH, line, MAX_LENGTH);
}
}
}
// Close the second file
fclose(file2);
// Write the modified buffer back to file1
fputs(buffer, file1);
// Close the first file
fclose(file1);
}
int main(void) {
replaceLines("c:\\LocationFolder\\Overwrite.txt", "c:\\LocationFolder\\Baseline.txt", "Simulated Primary Open", 3, 22);
return 0;
}
currently, I am writing code in c program for printing small portion of contents from the input file. Actually, in my code I can able to print just one single line. but, i have to print next 5 lines after that one line.
I am new to programming, please help to solve this problem**
code is given below
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int lineNumber = 2;
int main()
{
FILE *file;
char line[100];
int count = 0;
///Open LS-dyna file to read
file = fopen("P:\\tut_c\\read\\df-read\\in.txt", "r");
if (file == NULL)
{
perror("fopen");
exit(EXIT_FAILURE);
}
else if ( file != NULL )
{
char line[256];
while (fgets(line, sizeof line, file) != NULL)
{
if (count == lineNumber)
{
printf("\n str %s ", line);
fclose(file);
return 0;
}
else
{
count++;
}
}
fclose(file);
}
return 0;
}
The first logical error occurs in your while loop, first iteration, when you close the file and return 0.
Next, there is no reason to have a counter for your lines, since there are many c functions that can handle finding the end of file (eof).
Instead:
Use a while loop for iteration through the file.
Use a standard library c function for file reading.
Check if file has reached the end.
If the line is still valid, then print the line.
Here is some code to reiterate:
int main()
{
FILE *file;
file = fopen("file.txt", "r");
if (!file){ // check if file exists
perror("fopen");
exit(EXIT_FAILURE);
}
else { // if file exists, then...
char line[256];
while(fgets(line, sizeof line, file)){
printf("\n str %s ", line);
}
fclose(file);
}
return 0;
}// end main
I am trying to read from files and write to a temp file. However, I am stuck in an infinite loop right now. The function below is called multiple times by a recursive function that goes through directories to read files.
My approach is that I would read each word from one file, then those words to another file.
The function I have works fine if I just print out each word. It prints out each word in each file in all directories. However, when I try to start writing to a temp file (the code commented out), I am stuck in the while loop.
On the other hand, if I just call the function once in a test program where I just read from one file in the current directory, and write to a temp file, it's fine.
This is what I have (fileName when passed in is actually the absolute path, and I do ../tmp so it does not get caught in the recursion function):
void fileReadWrite(char *pattern, char *before, char *replace, char *fileName) {
FILE *file = fopen(fileName, "r");
if (file != NULL) {
int ch, word = 0;
while ((ch = fgetc(file)) != EOF) {
if (isspace(ch) || ispunct(ch)) {
if (word) {
word = 0;
putchar('\n');
}
}
else {
word = 1;
putchar(ch);
/*
FILE *f = fopen("../tmp", "wb"); // create and write
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
fprintf(f, "Some text"); // Or fprintf(f, ch);
fclose(f);
*/
}
}
fclose(file);
}
}
There's nothing in your code that suggests an infinite loop. However, if fileName is very large, you could be opening and closing "..\tmp" millions of times. As Joachim Pileborg points out in the comments, you should open that file just once at the beginning of your function, and close it again at the end.
If you want to convince yourself that you are not in an infinite loop, print out the value of ch on each iteration.
Okay so I did this and it worked. But I don't understand why though. Can someone explain it please?
void fileReadWrite(char *pattern, char *before, char *replace, char *fileName) {
FILE *file = fopen(fileName, "r");
FILE *f = fopen("../tmp", "wb"); // MOVE HERE
if (file != NULL) {
int ch, word = 0;
while ((ch = fgetc(file)) != EOF) {
if (isspace(ch) || ispunct(ch)) {
if (word) {
word = 0;
putchar('\n');
}
}
else {
word = 1;
putchar(ch);
/*
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
fprintf(f, "Some text"); // Or fprintf(f, ch);
*/
}
}
fclose(file);
fclose(f); // MOVE HERE
}
}
I am trying to print a certain line of a file in c. So far I think I am successfully reading line 8 of my text file but my question is how do I print that line using this code?
Thanks!!
this is the code so far:
int lineNumber = 8;
static const char filename[] = "Text.txt";
FILE *file = fopen(filename, "r");
int count = 0;
if ( file != NULL )
{
char line[256]; /* or other suitable maximum line size */
while (fgets(line, sizeof line, file) != NULL) /* read a line */
{
if (count == lineNumber)
{
//use line or in a function return it
//in case of a return first close the file with "fclose(file);"
}
else
{
count++;
}
}
fclose(file);
}
This works perfectly fine.
Are you missing the main function OR is it just the code snippet you have posted ?
int lineNumber = 8;
static const char filename[] = "Text.txt";
int main()
{
FILE *file = fopen(filename, "r");
int count = 0;
if ( file != NULL )
{
char line[256]; /* or other suitable maximum line size */
while (fgets(line, sizeof line, file) != NULL) /* read a line */
{
if (count == lineNumber)
{
//use line or in a function return it
// //in case of a return first close the file with "fclose(file);"
printf("\n str %s ", line);
fclose(file);
return 0;
}
else
{
count++;
}
}
fclose(file);
}
return 0;
}
Here is the code:
int main()
{
struct vinnaren
{
char vinnare[20];
int artal;
};
struct vinnaren v[10];
int inputrader;
int antalrader; //I want antalrader to be equal to the first
//line in test.txt(the first line is "5")
char file_name[256] = "test.txt";
char buf[512];
FILE *f = fopen(file_name, "r");
if (!f)
{
exit(0);
}
while (fgets(buf, sizeof buf, f))
{
printf("%s", buf);
}
fclose(f);
}
This is the code I have. I want to make it so that
antalrader = line1 in the file test.txt
How do I read a specific line from the file?
With this code you can read a file line by line and hence read a specific line from the text file:
lineNumber = x;
static const char filename[] = "file.txt";
FILE *file = fopen(filename, "r");
int count = 0;
if ( file != NULL )
{
char line[256]; /* or other suitable maximum line size */
while (fgets(line, sizeof line, file) != NULL) /* read a line */
{
if (count == lineNumber)
{
//use line or in a function return it
//in case of a return first close the file with "fclose(file);"
}
else
{
count++;
}
}
fclose(file);
}
else
{
//file doesn't exist
}
I got a really simple answer but I don't know if it is helping anyone:
int OpenCommand(int idOfCommand)
{
fscanf(file_ptr, "%[^idOfCommand]",a[idOfCommand]);
printf("%d\n", a[idOfCommand]);
system("pause");
return 0;
}