Meaning of "open_file:" in c? [duplicate] - c

This question already has answers here:
What does the colon signify in a C function?
(3 answers)
Closed 5 years ago.
I was going through some code demonstrating error handling in file operations.
I can't understand what does open_file: mean and what does the colon after "open_file" signify ?
#include <stdio.h>
main()
{
char *filename;
FILE *fp1, *fp2;
int i, number;
fp1 = fopen("TEST", "w");
for(i = 10; i <= 100; i += 10)
putw(i, fp1);
fclose(fp1);
printf("\nInput filename\n");
open_file: //What does this mean ?
scanf("%s", filename);
if((fp2 = fopen(filename,"r")) == NULL)
{
printf("Cannot open the file.\n");
printf("Type filename again.\n\n");
goto open_file;
}
elsefor(i = 1; i <= 20; i++)
{ number = getw(fp2);
if(feof(fp2))
{
printf("\nRan out of data.\n");
break;
}
else
printf("%d\n", number);
}
fclose(fp2);
}

It's a goto label, used 7 lines below. It could be called sandeep: for all the compiler cares.

It's a label to which the goto a few lines later jumps..

Related

Reading from file in C - Wrong output

I am writing a code to read from a file but it always prints wrong output.
The code is as follows:
int n;
struct threeNum num = { 0 };
FILE *fptr;
if ((fptr = fopen("input.txt", "rb")) == NULL) {
printf("Error! opening file\n");
// Program exits if the file pointer returns NULL.
exit(1);
}
for (n = 1; n < 5; ++n)
{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3);
}
fclose(fptr);
The struct is:
struct threeNum
{
char n1, n2, n3;
};
And the .txt file is:
1 2 3
5 6 7
6 6 9
5 5 5
8 7 2
And I always get zeros printed.
fread reads binary objects, but your file is text. You need to read text and then parse that (such as with fscanf, or fgets followed by sscanf).
// As #Arkku said, use fgets to read each line and sscanf to parse it.
#include <stdio.h>
#include <stdlib.h>
int main() {
int num[15];
int totalRead, i = 0;
char dataToRead[50];
FILE *fp;
if ((fp = fopen("file.txt", "r")) == NULL) {
printf("Error! opening file\n");
// Program exits if the file pointer returns NULL.
exit(1);
}
// read the file
while (fgets(dataToRead, 50, fp) != NULL) {
totalRead = sscanf(dataToRead, "%d%d%d", &num[i], &num[i+1], &num[i+2]);
puts(dataToRead);
i = i + 3;
}
// I used modulo so that after every 3rd element there is a newline
for (i = 0; i < 15; i++) {
printf("%d ", num[i]);
if ((i+1) % 3 == 0)
printf("\n");
}
return 0;
}

2D array working inside the loop but not working outside the loop

I have coded a formula to read the txt file, store it in array(1D) and then reading the array to calculate the moving average(2D). Program ask the user to input two values (k1 & k2) and calculate the moving average for every value from k1 to k2 (basically to find out the best value)
Following is the code
#include<stdlib.h>
#define MAX_FILE_NAME 100
#define MAXCHAR 1000
int main()
{
FILE *fp;
int count = 0,k1=0,k2=0,k=0; // Line counter (result)
int buy[k2][count],sell[k2][count];
char filename[MAX_FILE_NAME];
char c; // To store a character read from file
// Get file name from user. The file should be
// either in current folder or complete path should be provided
printf("Enter file name or full path: ");
scanf("%s", filename);
printf("Enter the minimum rolling period for calculation : \n");
scanf("%d", &k1);
printf("Enter the maximum rolling period for calculation : \n");
scanf("%d", &k2);
// Open the file
fp = fopen(filename, "r");
// Check if file exists
if (fp == NULL)
{
printf("Could not open file %s", filename);
return 0;
}
// Extract characters from file and store in character c
for (c = getc(fp); c != EOF; c = getc(fp))
if (c == '\n') // Increment count if this character is newline
count = count + 1;
// Close the file
fclose(fp);
//printf("The file %s has %d lines\n", filename, count);
FILE *myFile;
myFile = fopen(filename, "r");
//read file into array
float numberArray[count];
int i;
if (myFile == NULL){
printf("Error Reading File\n");
exit (0);
}
for (i = 0; i < count; i++){
fscanf(myFile, "%f,", &numberArray[i]);
}
fclose(myFile);
for (k=k1;k<=k2;k++)
{
float n;
float data[count],mag[k2][count];
double avg,sum;
for (i=0;i<k-1;i++)
{
mag[k][i-1]=0;
sum=sum+numberArray[i];
}
for(i=k-1;i<=count;i++)
{
mag[k][i-1]=avg;
sum=sum+numberArray[i]-numberArray[i-k];
avg = sum/k;
}
// for(i=0;i<=count;i++)
// {
// printf("MA[%d][%d] = %0.2lf ",k,i,mag[k][i]);
// if (i%3==0)
// printf("\n");
// }
}
for(k=k1;k<=k2;k++)
{
for(i=0;i<=count;i++)
printf("MA[%d][%d] = %0.2lf ",k,i,mag[k][i]);
}
}
}
Now when I am trying to print mag[k][i] values outside the for loop, it is showing error 'mag' undeclared. But when I am putting the print command inside the loop (comment out portion in the code), it works fine.
UPDATED CODE AFTER FOLLOWING COMMENTS (STILL NOT WORKING THOUGH)
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
#define MAX_FILE_NAME 100
#define MAXCHAR 1000
int main()
{
FILE *fp;
int count,k1,k2,k; // Line counter (result)
char filename[MAX_FILE_NAME];
char c; // To store a character read from file
// Get file name from user. The file should be
// either in current folder or complete path should be provided
printf("Enter file name or full path: ");
scanf("%s", filename);
printf("Enter the minimum rolling period for calculation : \n");
scanf("%d", &k1);
printf("Enter the maximum rolling period for calculation : \n");
scanf("%d", &k2);
// Open the file
fp = fopen(filename, "r");
// Check if file exists
if (fp == NULL)
{
printf("Could not open file %s", filename);
return 0;
}
// Extract characters from file and store in character c
for (c = getc(fp); c != EOF; c = getc(fp))
if (c == '\n') // Increment count if this character is newline
count = count + 1;
// Close the file
fclose(fp);
//printf("The file %s has %d lines\n", filename, count);
/****************
File opening and reading section
*****************************************************/
FILE *myFile;
myFile = fopen(filename, "r");
//read file into array
float numberArray[count];
int i;
if (myFile == NULL){
printf("Error Reading File\n");
exit (0);
}
for (i = 0; i < count; i++){
fscanf(myFile, "%f,", &numberArray[i] );
}
fclose(myFile);
/***********************************************
Calculation of Moving Average and storing it in array
******************************************/
int buy[k2][count],sell[k2][count];
float mag[k2][count];
for (k=k1;k<=k2;k++)
{
float data[count];
double avg,sum;
for (i=1;i<k;i++)
{
mag[k][i-1]=0;
sum=sum+numberArray[i];
}
for (i=k-1;i<=count;i++)
{
mag[k][i-1]=avg;
sum=sum+numberArray[i]-numberArray[i-k];
avg = sum/k;
}
// for(i=0;i<=count;i++)
// {
// printf("MA[%d][%d] = %0.2lf ",k,i,mag[k][i]);
// if (i%3==0)
// printf("\n");
// }
}
for (k=k1;k<=k2;k++)
{
for (i=0;i<=count;i++)
{
printf("MA[%d][%d] = %0.2lf ",k,i,mag[k][i]);
}
}
}
The problem boils down to this: the scope of mag is limited to the inside of the for loop:
for (k = k1; k <= k2; k++)
{
...
int mag[k2][count];
...
}
// mag is out of scope here
// therefore following line won't compile:
printf("%d", mag[0][0]);
You need to declare mag outside the for loop for example like this:
int mag[k2][count];
for (k = k1; k <= k2; k++)
{
...
}
printf("%d", mag[0][0]);
...
Beware: there are other problems within your code, mentioned in the comments.

Get number line of file text in c [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How do get number line of file text on c ?. Help me .
Get sum number line.
I want read a file text.
EX:
for( line = 0; line < sumline; line ++) {
printf("char in line");
}
In case i understood the question :
#include <stdio.h>
#include <string.h>
main()
{
FILE *fp;
char * line;
size_t len = 0;
ssize_t read;
int lines = 0;
fp = fopen("input.txt", "r");
if( fp != NULL ){
while ((read = getline(&line, &len, fp)) != -1){
lines ++;
printf("%s\n", line);
}
fclose(fp);
}
printf("number of lines : %d\n", lines);
}
to count how many lines in your file
Try this:
`int lines = 0;
while ((read = getline(&line, &len, fp)) != -1) {
lines++;
}
cout << lines << endl;`
You can use the following function to get the number of lines inside a file.
#include <stdio.h>
// get the number of lines inside file
int getLineCnt(char *pcFileName) {
FILE *fp;
int lines=0;
fp = fopen(pcFileName, "r");
if(fp == NULL) { return -1; }
while (EOF != (fscanf(fp, "%*[^\n]"), fscanf(fp, "%*c"))) {
++lines;
}
io_fclose(fp);
return lines; ///\ retval number of lines
}

Search for keyword in textual file C

I'm having trouble reading a keyword from file that a user inputs to search for. The first part of the program asks for user input for naming the file. It then asks for sentence input. You can input sentences until you write "END". When you write "END", the appending of sentences to file should stop and the program should ask you for a keyword to search the sentences appended to the newly created textual file. I used 'gets' to ask for a word that will be searched for in the file. The program should find that word in a sentence and print back the whole sentence containing the keyword. The whole code looks like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char fileName[128];
printf("Input your filename (end with .txt):");
gets(fileName);
FILE *filePointer = NULL;
char text1[128];
char word1[128];
filePointer = fopen(fileName, "a");
if(filePointer == NULL)
{
printf("Cannot open file!");
exit(EXIT_FAILURE);
}
else{
printf("Input your sentence: ");
while (fgets(text1, 127, stdin) != NULL && strncmp(text1, "END\n", 5) != 0){
printf("Input your sentence: ");
fprintf(filePointer, "%s", text1);
}
int line_num = 1;
int find_result = 0;
char text2[128];
filePointer = fopen(fileName, "r");
printf("Input keyword you're looking for: ");
gets(word1);
while(fgets(text2, 127, filePointer) != NULL) {
if((strstr(text2, word1)) != NULL) {
printf("A match found on line: %d\n", line_num);
printf("\n%s\n", tekst2);
find_result++;
}
line_num++;
}
if(find_result == 0) {
printf("\nSorry, couldn't find a match.\n");
}
if(filePointer) {
fclose(filePointer);
}
return(0);
}
}
It all works, but the problem is somewhere here:
int line_num = 1;
int find_result = 0;
char text2[128];
filePointer = fopen(fileName, "r");
printf("Input keyword you're looking for: ");
gets(word1);
while(fgets(text2, 127, filePointer) != NULL) {
if((strstr(text2, rijec)) != NULL) {
printf("A match found on line: %d\n", line_num);
printf("\n%s\n", text2);
find_result++;
}
line_num++;
}
I'm new at C programming, so I'm not sure where the flaw is. I know it should work in theory. It doesn't return a result when it clearly should.
You need to fclose() the file after writing, before reopening to read.
if (fclose(filePointer) != 0)
{
fputs("The sky is falling.", stderr);
return 1;
}
filePointer = fopen(fileName, "r");

read file in C and split string [duplicate]

This question already has answers here:
Split string with delimiters in C
(25 answers)
Closed 9 years ago.
I have a program that read File in C. Now I want to put the strings divide by space into an array. How do I do it?
#include <stdio.h>
int main()
{
char line[30];
char names[100][20];
int sizes[100];
int i = 0;
FILE *fp;
fp = fopen("in.txt", "rt");
if(fp == NULL)
{
printf("cannot open file\n");
return 0;
}
while(fgets(line, sizeof(line), fp) != NULL)
{
printf(line);
i++;
}
fclose(fp);
return 0;
}
Have a look at the function strtok or strtok_r
http://www.cplusplus.com/reference/cstring/strtok/?kw=strtok

Resources